簡體   English   中英

NodeJS,使用友好的URL時找不到CSS,JS

[英]NodeJS, can't find css, js when using friendly url

這是我關於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:當我使用網址“ / post_detail / 123”時,在控制台中有什么不同:網址“ / post_detail?id = 123”

GET /css/themes.css 304 7.313 ms - -

網址“ / post_detail / 123”

GET /post_detail/css/themes.css 404 38.535 ms - 965

包括jscss文件時,您似乎最有可能使用相對路徑而不是絕對路徑。

在您的視圖文件(也許是layout.html ,我只是在猜測項目的結構)中,請嘗試使用以正斜杠為前綴的網址:

<!-- 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 ,相對路徑可以正常工作,因為它們是相對於/但是當您訪問/post_detail/123它們現在相對於/post_detail/ ,並將請求帶有前綴/post_detail/的資源。

因此,請嘗試在您的視圖中使用絕對路徑,希望它能起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM