React 路由器和 Express GET 冲突

Jen*_*Mok 0 javascript node.js express reactjs react-router

我无法弄清楚反应路由器和快速路由如何一起工作。

我有这个

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);
Run Code Online (Sandbox Code Playgroud)

问题是我的 api 无法使用 GET,因为它会重定向到 index.html。如果我删除通配符路由,那么react-router将无法正常工作。

Pat*_*und 5

您的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');
});
Run Code Online (Sandbox Code Playgroud)

这样,任何以路径开头的请求都/api将由您的路由器处理apiRoutes,所有其他请求均由星号处理。