Home > OS >  Express isn't serving my static files when on a certain page
Express isn't serving my static files when on a certain page

Time:11-23

Express serves my static files just fine when I'm on my "/" and "/home" page, however when I go to "/home/download" my files are no longer served. Im using EJS to render my pages.

router.get("/download", isAuthed, (req, res) => {
    res.render("download", {
        username: req.user.username,
        discordId: req.user.discordId,
        avatar: req.user.avatar,
        discriminator: req.user.discriminator
    })
})

This is my /home router

and this is where I tell express to serve my public folder

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

If there is something I've left out that would help you figure out what is wrong please let me know thanks.

Update: I change to the /home/download page when a link is pressed on the /home page

<a  href="/home/download">Download</a>

If this is whats causing the files not to be served how can I then change pages.

CodePudding user response:

This is because your links in your web page are relative links (don't start with a /) which tells the browser to add the path of the current page to their URL before requesting them. That will mess up your static route handling.

As an example, if you had something like this:

<img src="image.jpg">

Then, when you were on /home/download, the browser would request:

/home/image.jpg

which would not work with your express.static() code because the image is not located in public/home/image.jpg

The usual fix is to add / to the front of all your static resource URLS in your HTML so the browser will not add the path of the current page to the URL when requesting it.

<img src="/image.jpg"> 

If you want further help, show us the actual HTML for the resource and show us where everything is in your server file system.

  • Related