Warm tip: This article is reproduced from serverfault.com, please click

Css not loading with req.params or maybe something else

发布于 2017-01-18 15:41:53

I'm very new to node, express etc. I've made a blog-app and i'm facing a problem. I'm using mongoose, node, express and ejs.

When i call

router.get('/posts', function(req, res){   Post.find({}, function(err, posts){
    res.render('viewpost.ejs', {
      posts
    });   }); });

Everything works perfectly fine. I got my posts and css is working as well. The problem is when i call

router.get('/posts/:posts_id', function(req, res){
  Post.find({_id: req.params.posts_id}, function(err, posts){
      res.render('viewpost.ejs',{
         posts
    });
  });
});

Post seems to be working but in console i got

GET /posts/posts.css 304 1.854 ms And the viewpost.ejs looks like it's not using the css.

Server file server.js

app.use(express.static('public'))
app.use(express.static(path.join(__dirname, 'public/css/')));
app.use(express.static(path.join(__dirname, 'public/img/')));

viewpost.ejs

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="style.css">
    <script src="/bower_components/jquery/dist/jquery.js"></script>
  </head>
  <body class="cyc">
  <% include ./partials/navbar.ejs %>

<%= posts %>
</body>
</html>

So when i use route without req.params everything seems to be working ok. When i call it with any param my css file is not working.

Questioner
Luke Bas
Viewed
0
Stefan Dragnev 2017-01-19 00:25:34

<link rel="stylesheet" href="style.css"> tries to load style.css from the same path where the HTML page is. So, for /posts, it will try loading /style.css and for /posts/1, it will try to load /posts/style.css. But the latter matches your /posts/:posts_id endpoint, so that gets called instead with posts_id == 'style.css', which is nonsensical.

The solution is quite simply to make the link absolute:

<link rel="stylesheet" href="/style.css">