Home > Mobile >  Serve static files with Node/Express
Serve static files with Node/Express

Time:11-30

I created a node express app and defined a path for static resources in my express app, app.ts:

app.use(express.static(path.join(__dirname, 'public')));

My static files are well served when I am on a main level, for example localhost:3000/products but I get a 404 return code on secondary paths, for example localhost:3000/products/details with this instruction:

<img src="images/image1.jpg"  alt="...">

What am I doing wrong?

Thank you in advance for your help.

CodePudding user response:

Don't use relative paths for your URLs in the page. Start them all with a /. Change this:

<img src="images/image1.jpg"  alt="...">

to this:

<img src="/images/image1.jpg"  alt="...">

When the path does not start with a /, then the browser adds the path of the containing page URL to the URL before requesting it from the server because ALL requests to the server must be absolute URLs. That makes things break as soon as you are no longer on a top level page. But, if your URLS always start with /, then the browser doesn't have to mess with the path of the URL before requesting it.

  • Related