【发布时间】:2017-08-17 05:36:25
【问题描述】:
我正在使用React BrowserHistory 进行导航。无论 URL 路径如何,我都希望从我的节点服务器提供相同的文件。
我的服务器代码:
const http = require('http');
const path = require('path');
const express = require('express');
const app = express();
const hostname = 'localhost';
app.use(express.static('../public'));
app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, '../public/index.html'));
});
const port = process.env.PORT || 8007;
app.listen(port, ()=>{
console.log('Production Express server running at localhost:' + port)
});
http://localhost:8007 => 工作正常
http://localhost:8007/help => 工作正常
http://localhost:8007/help/faq => 失败
我希望所有 URL 返回相同的资源,由 ../public 提供。但是,当没有从根请求资源时,express.static 似乎不起作用。因此,例如,当浏览器请求<script src="scripts/main.js"></script> 时,它认为我想要../public/help/scripts/main.js,而我实际上想要../public/scripts/main.js/。所以,因为 express 没有找到这样的文件,它会转到 app.get('*'...,当请求脚本时返回 ../public/index.html 文件。
所以,期望的行为是:
- 为任何路径(具有任意数量的子文件夹)返回相同的 index.html,并让 React 找出要显示的内容
- 返回的资源总是相对于提供 index.html 的路径,而不是相对于 URL 中的路径
当我在资源请求中使用绝对路径(即<script src="http://localhost:8007/scripts/main.js"></script>)时,它可以工作,但是这样写显然是不可取的,因为当它托管在其他地方时需要更改它。
我该怎么办?
【问题讨论】:
-
当您有相对 URL 要求这样的脚本时会发生这种情况,无论服务器如何,只需将其更改为
<script src="/scripts/main.js"> -
@adeneo 我简直不敢相信只是在它前面添加斜线就解决了它。
标签: javascript node.js express react-router browser-history