【问题标题】:How to separate React router and nodejs api如何分离 React 路由器和 nodejs api
【发布时间】:2017-01-16 10:45:53
【问题描述】:

我是 React 的新手,并尝试基于 https://github.com/lmammino/judo-heroes 引用的 reactjs + expressjs + nodejs 开发示例应用程序,但问题是当我尝试为 3rd 方应用程序创建 webhook api 时,react router 向我展示了作为 404 页面。

server.js

import routes from './routes';
...
...
var webhook = require('./routes/webhook');
app.use('webhook', webhook);

routes.js

'use strict';

import React from 'react'
import { Route, IndexRoute } from 'react-router'
import Layout from './components/Layout';
import IndexPage from './components/IndexPage';
import NotFoundPage from './components/NotFoundPage';

const routes = (
  <Route path="/" component={Layout}>
    <IndexRoute component={IndexPage}/>
    <Route path="*" component={NotFoundPage}/>
  </Route>
);

export default routes;

当我调用“localhost:3333/webhook”时,它会执行&lt;Route path="*" component={NotFoundPage}/&gt;,如显示404错误页面。

请帮助我如何将 webhook 导出为与反应路由器无关的单个 api?

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    发生这种情况是因为您尝试以与服务器端相同的方式呈现客户端路由,这导致 React + Express 中的路由之间发生冲突。我建议您可能正在使用browserHistory,我会换成hashHistory,因为这意味着客户端的渲染方式与快速路由不同。通过交换以散列您的反应路线,通过/#/index 呈现。这允许 express 以传统格式(如 /api/webhook)呈现 API 路由。你可以在这里阅读更多关于历史的信息https://github.com/ReactTraining/react-router/blob/master/docs/API.md#histories

    希望对你有帮助

    迪伦

    【讨论】:

      【解决方案2】:

      您应该使用前导斜杠安装webhook 路由器:

      app.use('/webhook', webhook);
      

      这应该在app.get('*', ... 通配符处理程序之前执行,以防止 React 应用程序被服务和引导。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-30
        • 1970-01-01
        相关资源
        最近更新 更多