I have a page asking for these files
<link rel="stylesheet" href="/vendor/css/style.css">
<script type="text/javascript" src="/vendor/js/app.js"></script>
and I've set up the express static route as follows
express = require 'express'
app = express()
app.use '/vendor/js', express.static './node_modules/framework/'
app.use '/vendor/css', express.static './otherFramework/'
app.get '/page/:num', (req, res) ->
page = parseInt req.params.num, 10
res.render 'list', #list is a jade file that extends a common layout.jade, the same as the '/' route
start: page
end: ++page
return
when I open the page '/' everything works fine, but now I want to implement another MVC-like route like '/page/:num', and express is asked this new route as base path for my requested external files, ex: (from the server log)
/page/1/vendor/css/style.css - 200
and this obviously doesn't work.
How can I tell express to search in the root? I tried to use a ~ before the path but it didn't work.
in the app.js (main file) file,before application routes, add these lines :
app.get('*/vendor/css/style.css', function (req, res) {
res.sendFile(__dirname + '/vendor/css/style.css');
});
app.get('*/vendor/js/app.js', function (req, res) {
res.sendFile(__dirname + '/vendor/js/style.js');
});
#akram-saouri 's answer was almost exact: I ended up using this configuration:
app.use '*/vendor/js', express.static './node_modules/framework/'
app.use '*/vendor/css', express.static './otherFramework/'
for all the app and it worked like a charm
Related
So i have a problem with my static files. Here's my code:
const express = require ('express')
const app = express()
app.listen(4040,() => console.log("on"))
app.use(express.static(__dirname + "/public"))
Everything works. Until I change html file name in public folder
It works if it's index.html but doesn't if it's about.html or everything else.
My folders are like that:
📂Main
📂node_modules
📂public
📂assets
style.css
index.html/about.html
main.js
package-lock.json
package.json
Route must be specific, "/" for "index.html" & "/about" for "about.html". If you change from index.html to home.html, make sure your main.js (server) also follows.
const express = require("express");
const path = require("path");
const app = express();
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "public/about.html"));
});
app.listen(4040, () => console.log("on"));
index.html (http://localhost:4040/)
<h1>HOME PAGE</h1>
about.html (http://localhost:4040/about)
<h1>ABOUT PAGE</h1>
Hey I believe I might know what's going on but wanted to clarify, you are wanting to serve multiple static files one "index.html" and another "about.html" and it's only working for the one called index.html? If this is the case this is because it defaults to reading the index.html file if it is present, the solution to this may be to rename your index.html to something else such as main.html, and see if that works properly.
I am developing an application and I have defined my custom routes in a different way. I am using Web Storm IDE to develop and it has a specific folder of routes where all the routes are kept individually. I have the following code in my directory /routes/about.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('about', { title: 'About Us' });
});
module.exports = router;
Now in the app.js I have written the following code to include these route and use it:
var index = require('./routes/index');
var users = require('./routes/users');
var about = require('./routes/about');
app.use('/', index);
app.use('/users', users);
app.use('/about', about);
But when I click on about link, it does not open the page. Though, if I write the route in the app.js file directly as:
app.get('/about', function (req, res) {
res.render('about');
});
then it renders the page. Also, if I do not make separate routes and use the default routes file (/routes/index.js) and include this in that file, then also the code works fine. Can anyone explain or tell is there any mapping of these route files done which is missed by me, or I am doing something syntactically wrong
You probably created a route for /about/about. To fix, change the about router from this:
router.get('/about', ...);
to this:
router.get('/', ...);
This, then goes with:
app.use('/about', router);
which already includes the /about path. Everything in that router will already have /about at the beginning of the path.
Use below code in about file
app.get('/', function (req, res) {
res.render('about');
});
You have already defined '/about' route in main file so if you want to render page on '/about' so you need to define route like this '/' in about page.
For example route '/about/us' then function will be in about page :
app.get('/us', function (req, res) {
res.render('about us');
});
The method to redirect the route is correct, but you have not pass the route to app.
so you just need to do is ,
router.use('/about', about);
app.use('/', router);
Like wise add router in app
I have a basic project set up with server.js in my root with this code:
app.use('/', express.static(__dirname + '/public/'));
Additionally I have a public folder with index.html, styles and scripts folder in that dir root.
I'd like my web application to send users to index.html regardless of any url paramaters they might have. For example: If a user tries to go to localhost:8888/notarealpage it still loads index.html (without a redirect) so I can still reference the 'notarealpage' in the location.href property.
You can use:
app.get('*', function (req, res) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
This way, it will send your index.html no matter the URL.
Please notice you might have to fine tune the sendFile parameter.
Adding
app.get('*', function (req, res) {
res.sendFile((__dirname + '/public/index.html'));
});
to the end of my routes in server.js did the trick.
I was having trouble settings up a very basic static file sever using express with Node.js. I set up a simple server.js but cannot see any files when I load the URL localhost:9000 in my web browser.
All I see is a page saying: Cannot get /
var express = require('express');
var app = express();
app.use(function(req, res, next) {
next();
});
app.use(express.static(__dirname));
app.listen(9000);
Simply you're exposing nothing. Do you have, for example, an index.html file? Try this:
app.get("/", function(req, res) {
res.sendfile("index.html");
});
Did you go through the NodeSchool workshoppers? They have step-by-step examples that cover this and more.
Here is the workshop for Express.
Here is my solution for the 'static' question in the workshop.
var express = require('express')
var app = express()
app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));
app.use(require('stylus').middleware(__dirname + '/public'));
app.post('/form', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
})
app.listen(process.argv[2])
Express does not create a directory listing. Even thought it does not list the files in the directory, it does serve them up when hitting them in the web browser.
Point the browser to the actual file:
http://localhost:9000/public/test.html
Originally I found this confusing because I had expected the express server to list directories; when seeing "something"... a page that said "Cannot get /" I assumed that page would normally have a list of files.
I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.