CSS没有用req.params或其他东西加载 [英] Css not loading with req.params or maybe something else

查看:75
本文介绍了CSS没有用req.params或其他东西加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对节点,快递等还很陌生.我制作了一个博客应用,现在遇到了问题.我正在使用猫鼬,节点,快递和ejs.

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.

当我打电话时

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

一切正常.我收到了我的帖子,css也正常工作.问题是当我打电话

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毫秒而且viewpost.ejs看起来好像没有使用CSS.

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

服务器文件 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>

所以当我使用没有req.params的路由时,一切似乎都在工作好的.当我用任何参数调用它时,我的css文件不起作用.

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.

推荐答案

< link rel ="stylesheet" href ="style.css"> 尝试加载 style.css从与HTML页面相同的路径开始.因此,对于/posts ,它将尝试加载/style.css ;对于/posts/1 ,它将尝试加载/posts/style.css .但是后者与您的/posts/:posts_id 端点匹配,因此可以使用 posts_id =='style.css'进行调用,这是荒谬的.

<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">

这篇关于CSS没有用req.params或其他东西加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆