omid
omid

Reputation: 43

Path problem in URL ( absolute and relative )

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)



Upvotes: 0

Views: 1489

Answers (1)

jfriend00
jfriend00

Reputation: 707158

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:

http://localhost:3000/5

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.

Upvotes: 1

Related Questions