I am trying to serve static files (CSS stylesheets) with Express, and it is located when I am on some routes such as the home page /
or index page /index
. However, when I navigate to a /index/:id
page, I get this error in the chrome console:
GET http://localhost:3000/index/stylesheets/styles.css net::ERR_ABORTED
I'm sure that the reason why I am getting this error is because the css file is not actually served in the location stated in the error. I verified that the actual location that it is being served is http://localhost:3000/stylesheets/styles.css
.
I have this following line of code in my server file: to serve the css file app.use(express.static(__dirname + "/public"));
and this is the code for the /index/:id
route:
app.get('/index/:id', function(req, res) {
Post.findById({_id: req.params.id}, function(err, foundPost){
if (err) {
console.log(err);
res.redirect('/');
}
else {
res.render('./index/show', {post: foundPost});
}
});
});
and I made sure to add the CSS to every html page being served with this exact line: <link rel="stylesheet" href="stylesheets/styles.css" />
Why is the CSS included for routes such as /
or /index
, but looks in the wrong place for it when I navigate to a /index/:id
page? The location that the page is looking for the css file in changes from http://localhost:3000/stylesheets/styles.css
to http://localhost:3000/index/stylesheets/styles.css
depending on the route I am on.
What am I missing? Any help is much appreciated!
这对我有用
app.use(express.static('public'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.