NodeJS,使用友好的url时,找不到CSS,JS
这是我的第一个问题在stackoverflow,我的英语如此糟糕,对此感到遗憾。
在nodejs应用程序中,当我使用像“/ post_detail?id = 123”
app.get('/post_detail', function(req, res) { res.render("post_detail", {id: req.param("id")}) });
没关系,我将在post_detail页面中加载所有js和css:
GET /css/main.css 304 7.194 ms - - GET /css/themes.css 304 7.313 ms - - GET /js/vendor/bootstrap.min.js 304 8.139 ms - - GET /js/plugins.js 304 8.810 ms - - GET /js/app.js 304 16.648 ms - -
但是,当我使用“/ post_detai / 123”和路由器:
app.get('/post_detail/:id', function(req, res) { res.render("post_detail", {id: req.param("id")}) });
在控制台中给出了以下错误:
GET /post_detail/css/themes.css 404 38.535 ms - 965 GET /post_detail/css/main.css 404 38.817 ms - 965 GET /post_detail/js/vendor/bootstrap.min.js 404 28.060 ms - 965 GET /post_detail/js/plugins.js 404 19.449 ms - 965 GET /post_detail/js/app.js 404 16.454 ms - 965
那么,如何解决这个问题? 请帮帮我。 🙁
谢谢你的帮助。
P / S:当我使用URL“/ post_detail / 123”,在控制台中是否有任何区别:Url“/ post_detail?id = 123”
GET /css/themes.css 304 7.313 ms - -
url“/ post_detail / 123”
GET /post_detail/css/themes.css 404 38.535 ms - 965
看起来你最有可能使用相对path而不是绝对path时,包括你的js
和css
文件。
在你的视图文件(可能是layout.html
,我只是猜测你的项目的结构)尝试使用前缀正斜杠的URL:
<!-- This --> <link href="/css/main.css"> <script src="/js/app.js"></script> <!-- Rather than this --> <link href="css/main.css"> <script src="js/app.js"></script>
当你在/post_detail?id=123
,相对path工作正常,因为它们是相对于/
但是当你访问/post_detail/123
它们现在是相对于/post_detail/
并且将请求具有前缀/post_detail/
的资源。
所以尝试在你的视图中使用绝对path,我希望它的作品。