2

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?

Luke
  • 2,976
  • 6
  • 34
  • 44

1 Answers1

3

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. :)

timolawl
  • 5,434
  • 13
  • 29
  • It seems like `/dist` tries to search for the files in the root of the project (the folder where I keep the gulpfile.js and package.json) when I run the app in localhost mode! – Luke May 03 '16 at 18:08
  • It should resolve to `http://mywebsite.com/dist/bundle.min.css` or `localhost:port/dist/bundle.min.css`. The first forwardslash means it is based on the root. See: http://stackoverflow.com/a/21828923/5812121 http://stackoverflow.com/a/10659501/5812121 – timolawl May 03 '16 at 18:16
  • 1
    Your answer is correct, thanks! My error was also declaring BASE to spin up the server! ```server.use(BASE, express.static(__dirname + BASE, { extensions: ['html'] }))``` – Luke May 03 '16 at 18:44