[英]Node / Express - Serve-static not working / How to use routes with serve-static files
[英]How to serve static files to different routes in Express?
我正在使用Express创建站点,当我尝试使用超过一个级别的路由时,没有任何静态文件得到服务。 例如,这是我的代码,可以正常工作:
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}!`))
我想在路径中使用如下所示的内容:
app.get('/admin/organizations', (req, res) => res.sendFile(__dirname + '/organizations.html') )
我尝试弄乱了app.use
函数,因为我认为这就是我的问题所在,但到目前为止我仍无法弄清楚。 如何将静态文件提供给任何路由?
编辑:这是相关的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>
这与relative
路径有关。 通过express
,使用absolute
路径更安全 。
在您的路由深入一层之后,发送的html文件需要向上搜索一级以找到静态文件。 (您可以确认: ../public/global.css
实际上会在您的路由/admin/organizations
正确链接静态文件)
简单修复:使用绝对路径(注意,它仅以/
开头)
<link rel="stylesheet" type = "text/css" href = "/public/global.css"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.