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>
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"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.