I have a local website with "Nodejs" (using "Express" framework). I'm using express route for showing each file in my directory and if the file that requested isn't in my directory I want to render not-found.html
. But I realized a weird things happen. Here it's the issue:
when user enter something like this: " http://localhost:3000/swgw " the last middleware execute and "not-found.html" render property. (with css style)
when user enter URL like following pattern: " http://localhost:3000/products/ *" the problem is this time not-found.html
render without css style. ( Note: * isn't 1-6)
server.js
server.js
``` ... app.use(express.static(path.join(__dirname, 'public'))); app.get("/products/:id", (req, res, next) => { // since I have six product with id from 1 to 6. if (req.params.id <= 6 && req.params.id >= 1) { res.setHeader('content-type', 'text/html'); return res.sendFile(path.resolve(`public/products/product-${req.params.id}.html`)); } else { next(); } }); app.get('*', function(req, res){ res.status(404); res.sendFile(path.resolve('public/not-found.html')); }); ```
not-found.html ... <link rel="stylesheet" href="./style/not-found.css" > ...
Change to
<link rel="stylesheet" href="/style/not-found.css" >.
You want a path that is relative to the public directory that express.static()
has as its root.
But may u please explain me in case href="./style/not-found.css" why it's works correctly when user enter : "localhost:3000/5" but not work on "localhost:3000/products/5" (I mean loading css successfully)
When the link your HTML page does not start with http://
or with /
, then it is considered a path-relative link and the browser will take the path of the page and combine it with the URL in the link to make a full URL before sending it to the server. So, when you have this:
href="./style/not-found.css"
and the page URL is this:
http://localhost:3000/products/something
The browser will end up requesting:
http://localhost:3000/products/style/not-found.css
And, your server won't know what to do with that. On the other hand, when you change the <style>
tag to this:
href="/style/not-found.css"
Then, your URL starts with a /
so the only thing the browser will add to it is the domain and the browser will request:
http://localhost:3000/style/not-found.css
which will work.
So, when you use a path like:
Then, the path for that is just /
so when you combine /
with ./style/not-found.css
, the browser will end up requesting
http://localhost:3000/stye/not-found.css
and it will work because the path was a root path. So, it doesn't work for pages that are not at the top level. This is why your static resource URLs should always be path absolute (start with a /
) so they don't depend upon the path of the hosting page.
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.