0

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 ?

  • 1
    Maybe this will answer your question: https://stackoverflow.com/a/24582622/5833816 – Lazar Nikolic Sep 01 '20 at 09: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. – Anh Tuấn Phạm Sep 01 '20 at 09:09

2 Answers2

2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
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.

jaSnom
  • 71
  • 4
  • What bothers me is why was the relative path changed ? The htmls are in the same directory, only the url is changed. – Anh Tuấn Phạm Sep 01 '20 at 09:18
  • The path is relative to your current path `/category` becomes your new root path, since you are redirecting towards it. – jaSnom Sep 01 '20 at 09:20