【发布时间】:2020-07-04 15:01:01
【问题描述】:
我有一个带有“Nodejs”的本地网站(使用“Express”框架)。我正在使用快速路由来显示我的目录中的每个文件,如果请求的文件不在我想要呈现的目录中
not-found.html。
但我意识到奇怪的事情发生了。
问题来了:
当用户输入如下内容时:“http://localhost:3000/swgw”最后一个中间件执行和“not-found.html”渲染属性。 (带有 css 样式)
当用户输入如下模式的 URL 时:“http://localhost:3000/products/*”问题是这次 not-found.html 渲染没有 css 样式。 (注意: * 不是 1-6)
- 公开
- 产品
- product-1.html
- product-2.html
- product-3.html
- product-4.html
- product-5.html
- product-6.html
- 风格
- not-found.css
- not-found.html
- 产品
-
server.js
server.js``` ... app.use(express.static(path.join(__dirname, 'public'))); app.get("/products/:id", (req, res, next) => { // since I have six product with id from 1 to 6. if (req.params.id <= 6 && req.params.id >= 1) { res.setHeader('content-type', 'text/html'); return res.sendFile(path.resolve(`public/products/product-${req.params.id}.html`)); } else { next(); } }); app.get('*', function(req, res){ res.status(404); res.sendFile(path.resolve('public/not-found.html')); }); ```
not-found.html... <link rel="stylesheet" href="./style/not-found.css" > ...
【问题讨论】:
-
更改为
<link rel="stylesheet" href="/style/not-found.css" >。您需要一个相对于express.static()根目录的public目录的路径。 -
谢谢,我的问题解决了。但是请你解释一下
href="./style/not-found.css为什么当用户输入时它可以正常工作:“localhost:3000/5”但不能在“localhost:3000/products/5”上工作(我的意思是成功加载css) -
查看我在下面回答中的解释。
-
您似乎只提供静态文件,完全放弃您的服务器代码并简单地使用 [http-server](使用 npmjs.com/package/http-server)会更简单
标签: javascript node.js express path