2K01B5
2K01B5

Reputation: 1121

Url affecting the serving of static files when using Express

One of my pages has the url of '/artist/somename' and when that page is served there are images with the href of 'images/somename/1.jpg'. When the images are being requested, they're being requested with the url of '/artist/images/somename/1.jpg', which means that when the server looks for the image assets it cannot find them.

I've set up the express app so that

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

The images are stored in 'public/images/....'.

Any ideas as to how to resolve this would be much appreciated.

Upvotes: 0

Views: 56

Answers (1)

jfriend00
jfriend00

Reputation: 707326

If you don't want your image URL to be dependent upon the URL of the page they are hosted in, then don' use path relative URLS. Use only root relative URLS that start with /.

For example, make the href be: href='/images/somename/1.jpg'.

If the URL does not start with a /, then the browser will take the path from the URL and preprend that to your URL and that's what it will ask the server for. Thus, without the /, the URL the browser requests from the server will vary depending upon the hosting page.

Upvotes: 4

Related Questions