简体   繁体   中英

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

this is my first question on stackoverflow, and my english so bad, sorry about that.

In nodejs application, when i using url like "/post_detail?id=123"

app.get('/post_detail', function(req, res) {
    res.render("post_detail", {id: req.param("id")})
});

It's ok, i will load all js and css in post_detail page:

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

But, when i using "/post_detai/123" and router:

app.get('/post_detail/:id', function(req, res) {
    res.render("post_detail", {id: req.param("id")})
});

In console gives the below errors:

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

So, how to solve this problem? Please help me. :(

Thanks for your help.

P/S: when i'm using url "/post_detail/123", in console is there any difference: 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

It looks like you are most likely using relative paths rather than absolute paths when including your js and css files.

In your view file (perhaps layout.html , I'm only guessing at the structure of your project) try using urls prefixed with a forward slash:

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

When you are on /post_detail?id=123 the relative paths work properly, since they are relative to / but when you visit /post_detail/123 they are now relative to /post_detail/ and will request the resources with a prefixed /post_detail/ .

So try and use absolute paths in your view and I hope it works.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM