![](/img/trans.png)
[英]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.