Luke
Luke

Reputation: 3046

Relative paths for a 404 page served with Express

I'm serving a 404 page with Express:

server.use(function(req, res, next) {
  res.status(404).sendFile('404.html', { root: __dirname + BASE })
})

The 404.html is located in the website's root, and everything work flawlessly if I try to open a non-existent page on the root (http://mywebsite.com/asd).

Problem is when I try to open a page inside other folders (http://mywebsite.com/asd/asd). The paths for my css and js aren't respected: <link href="dist/bundle.min.css" rel="stylesheet">

How to solve this path related problem? And is it safe to to serve the page with sendFile on a production server?

Upvotes: 2

Views: 211

Answers (1)

timolawl
timolawl

Reputation: 5564

I believe you need a forwardslash in front of your href link:

<link href="/dist/bundle.min.css" rel="stylesheet">

As / is interpreted as the root of the hostname:

  • dist/bundle.min.css is relative to the path.
  • /dist/bundle.min.css is relative to the root.

Edit: Right. If you specify a base, then the root is set to that base. :)

Upvotes: 3

Related Questions