我无法弄清楚 react 路由器和快速路由如何一起工作。
我有这个
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
问题是我的 api 无法使用 GET,因为它会重定向到 index.html。如果我删除通配符路由,那么react-router将无法正常工作。
最佳答案
您的 app.get('*')
语句将匹配传入的任何请求。您可以通过更改语句的顺序来解决问题:
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
这样,任何路径以 /api
开头的请求都将由您的 apiRoutes
路由器处理,所有其他请求均由星号处理。
关于javascript - React 路由器和 Express GET 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43557390/