【问题标题】:react router and express GET conflict反应路由器和表达 GET 冲突
【发布时间】:2017-09-19 07:44:57
【问题描述】:

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

我有这个

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 将无法正常工作。

【问题讨论】:

  • 只需更改顺序。先放你的api 路线,然后放* 路线

标签: javascript node.js reactjs express react-router


【解决方案1】:

您的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 路由器处理,所有其他请求都由星号处理。

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2017-04-11
    • 2018-11-30
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多