【发布时间】:2016-09-26 23:22:46
【问题描述】:
这是我的项目结构:
-backend
-server.js
-www
-index.html
-app.css
-bundle.js
我遇到问题,Express 无法提供带有 2 个以上斜杠的 URL 的静态文件
localhost:3000/product/1
但它适用于只有 1 个斜杠的 URL:
localhost:3000/register
localhost:3000/home
问题发生,因为它总是试图获取
localhost:3000/product/1/app.css
和
localhost:3000/product/1/bundle.js
什么时候去
localhost:3000/product/1
这是我在 server.js 中的配置:
app.use(express.static(path.resolve(__dirname, '../www')));
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, '../www', 'index.html'))
});
【问题讨论】:
-
确保在 HTML 中链接到“/app.css”,而不仅仅是“app.css”。后者将在当前 URL 而不是从根目录中查找 app.css。这听起来不像是静态资产的问题。
-
同意@danneu。如果您使用 /filename.ext 引用具有根上下文的静态文件,那么一切都应该正常。
-
我实际上在我的索引文件中使用了“./app.css”和“./bundle.js”。我认为这不应该导致问题。
-
再试一次。事实证明“/bundle.js”有效。谢谢@danneu 和 flexdinesh :)
-
@sharius2301 fwiw, "./app.css" 和 "app.css" 都表示“在当前路径查找 app.css”,路径是 url 栏中的任何内容。 “/app.css”表示从根目录进行绝对查找,即忽略url栏中的当前路径。