0
我正在使用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(与任意数量的子文件夹),并让它再反应弄清显示
- 回报的资源总是相对于index.html的是从,不相服的路径在URL
它的工作原理,当我用我的资源请求(即<script src="http://localhost:8007/scripts/main.js"></script>
)绝对路径的路径,但是写这样说,这显然ISN”因为它需要ch当它被托管在其他地方时变得黯淡
我该怎么办?
这就是当你有相对URL请求这样的脚本时会发生什么,不管服务器如何,只要把它改成'