I want a route called 'main' which will serve static files:
app.use('/main',express.static(__dirname+'/public'));
However when i do:
http://my.site.dev/main
The CSS and JS files won't download because it is trying to get them from
http://my.site.dev/css/styles.css
It should be getting the files from:
http://my.site.dev/main/css/styles.css
However, if I access my site with a trailing slash:
http://my.site.dev/main/
All files come through fine
Any ideas why not having a trailing slash messes up resources like CSS and JS from coming in?
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.
A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.
In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.
use() function executes middleware in order. The express. static() middleware returns an HTTP 404 if it can't find a file, so that means you should typically call app.
This is an http problem, not just an Express-related challenge. The problem is discussed at:
If your URL is /main and your relative URL is css/style.css, it will resolve to /css/style.css; but if your URL is /main/, the relative URL resolves to /main/css/style.css.
My strategy for dealing with this is to redirect to add the trailing slash. Like this in Express:
app.all(/^\/main$/, function(req, res) { res.redirect('/main/'); });
app.use('/main/',express.static(__dirname+'/public'));
Or:
app.enable('strict routing');
app.all('/main', function(req, res) { res.redirect('/main/'); });
app.use('/main/',express.static(__dirname+'/public'));
How are the JS/CSS files requested in the HTML? If you're using strings like css/styles.css
, then it will try to get them from the current directory. The directory for /main
is /
(just like /main.html
would be), while the one for /main/
is /main/
. A quick fix would be to use /main/css/styles.css
in your HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With