2

I am creating a site using Express, and when I try to use routes more than one level deep, none of my static files get served. For example, here is my code that is working correctly:

const express = require('express') const app = express() const port = 3000 app.use('/public', express.static(__dirname + '/public')) app.get('/newSite', (req, res) => res.sendFile(__dirname + '/newSite.html') ) app.get('/organizations', (req, res) => res.sendFile(__dirname + '/organizations.html') ) app.listen(port, () => console.log(`listening on port ${port}!`)) 

I wanted to use something like this for the path:

app.get('/admin/organizations', (req, res) => res.sendFile(__dirname + '/organizations.html') ) 

I tried messing around with the app.use function because I am thinking that is where my issue is, but I haven't been able to figure it out so far. How do I serve static files to any route?

Edit: Here is the relevant html

<html> <head> <link rel="stylesheet" type = "text/css" href = "./public/global.css"/> <link rel="stylesheet" type = "text/css" href = "./public/organizations.css"/> </head> <body> </body> <script src = "public/jquery.js"> </script> <script src = "public/organizations.js"> </script> </html> 
4
  • Try app.use('/public(/*)?', express.static(__dirname + '/public')). Does that work? Commented Apr 25, 2019 at 16:45
  • I tried and it did not work. It stopped serving static files for my 'newSite' page as well after the change. Commented Apr 25, 2019 at 16:52
  • could you post a sample html page how you've linked Commented Apr 25, 2019 at 17:02
  • Sure, it's there now Commented Apr 25, 2019 at 17:06

1 Answer 1

3

It's got to do with relative path. With express it's safer to use absolute path.

After your route goes one level deep, the html file which is send needs to search one level up to find the static files. (You can confirm: ../public/global.css will actually link static files correctly in your route /admin/organizations)

Simple fix: use absolute path (notice it starts only with /)

<link rel="stylesheet" type = "text/css" href = "/public/global.css"/> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.