1

I have an application which serves html and looks like this.

// ... 
var staticPath = config.development.staticFiles;
app.get('/category/:catName', function(req, res) {
    res.sendFile(path.join(__dirname, staticPath + "shop-grid.html"));
})

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, staticPath + "index.html"));
})  
// ...

In each html, the css are linked like this .

<link rel="stylesheet" href="css/style.css" type="text/css">

The index.html works fine, but the "shop-grid.html" does not load with css, because it tried to load css at "localhost:8080/category/css/style.css" instead of "localhost:8080/css/style.css", which works for the first html.

What did i do wrong here ?

2
  • 1
    Maybe this will answer your question: stackoverflow.com/a/24582622/5833816 Commented Sep 1, 2020 at 9:05
  • @LazarNikolic like i said, the same thing works for "index.html", i guess using the different path ("/category" instead of "/") also changes the path which html loads css ? The link you posted didnt help. Commented Sep 1, 2020 at 9:09

2 Answers 2

3

What bothers me is why was the relative path changed ? The htmls are in the same directory, only the url is changed.

The browser knows nothing about how you have stored files on the server.

It only knows about URLs.

css/style.css is a relative path.

Relative paths are resolved by taking the URL of the current page, removing everything after the last / in the path, then appending the relative path.

http://localhost:8080/ + css/style.css = http://localhost:8080/css/style.css

http://localhost:8080/category/cats + css/style.css = http://localhost:8080/category/css/style.css


Use an absolute path: /css/style.css.

Absolute paths are resolved by removing the entire path (i.e. everything after the hostname and (if present) port number) and then appending the absolute path.

Sign up to request clarification or add additional context in comments.

Comments

0

You are redirecting both cases and therefore chaning your _dirname. but when you load the shop-grid.html, you are redirecting to another directory entirely. the href path isnt global its a relative path.

2 Comments

What bothers me is why was the relative path changed ? The htmls are in the same directory, only the url is changed.
The path is relative to your current path /category becomes your new root path, since you are redirecting towards it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.