我有一个快速后端的react前端。express只提供生产环境中react端的静态构建文件。我在生产中遇到了React路由工作的问题,就像许多人所遇到的那样,所以我修复了它:
server.js:
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
app.get('/api/customers', (req, res) => {
const customers = [
{id: 2, firstName: 'Test', lastName: 'Case'},
{id: 3, firstName: 'Foo', lastName: 'Bar'},
];
res.json(customers);
});'/*‘解决了生产环境中的路由问题,但现在'/api/customers’的fetch不再工作。
customer.js:
componentDidMount() {
fetch('/api/customers')
.then(res => res.json())
.then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)))
.catch(() => console.log('Error'));
}此获取请求在运行时会记录“错误”。由于server.js中'/*‘的变化,应用程序接口的url似乎发生了某种程度的变化,但我不确定应该如何更改fetch参数才能使其工作。fetch仅使用‘/’即可工作:
server.js:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});然而,这显然会阻止react路由在生产中工作。我需要将fetch参数更改为什么才能使其正常工作?
发布于 2018-03-19 00:13:53
更改server.js中路由的顺序
app.get('/api/customers', () => {});
app.get('/*', () => {});express中的路由是first come first served,当"/api/customers“匹配"/*”时,如果你的列表与之相反,它将返回你的index.html。
发布于 2019-10-27 05:51:25
非常感谢你的这个解决方案@David Filipidisz!顺序确实会影响路由。这是我的工作代码
server.js
这里是...ipmorts。
app.use('/users', require('./users/users.controller'));
app.use('/machineLearning', require('./machineLearning/machineLearning.controller'));
app.use('/public', require('./public/public.controller'));
//for Prod
app.use(express.static(path.join(__dirname,'../L10-ui/dist')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '../L10-ui/dist', 'index.html'));
});```https://stackoverflow.com/questions/49349153
复制相似问题