javascript - React Router 服务器端的错误处理

标签 javascript express reactjs react-router

我正在开发同构应用程序 react-router & express 。我在服务器端渲染中使用 react 路由器。我想要自定义错误页面,该页面将在服务器端错误、渲染错误或当然找不到时发送。但我在连接这些点时遇到了问题。 这是我的路线:

<Route component={Index} path="/">
  <IndexRoute component={Home} />
  <Route component={Chart} path="chart" />
  <Route component={Login} path="login" />
  <Route component={Error} path="error" /> //path="*" takes care only for not found,
                                             and it still sends the client a 200 status code
</Route>

这是我唯一的快速路线:

app.use((req, res, next) => {
  const location = createLocation(req.url);
  const css = [];
  match({ routes, location }, (err, redirectLocation, renderProps) => {
    if (err) {
      //500 internal error
      return next(err);
    }
    if(redirectLocation){
      //react-router redirect, no problems here
      return res.redirect(redirectLocation.path + redirectLocation.query);
    }
    if (!renderProps){
      //404 not found
      let error = new Error();
      error.message = "Not Found";
      error.status = 404;
      return next(err);
    }

    res.status(200).end(getHtml(renderProps));
  }
}

//...
//some regular express error handler to log in console and (as of right now) send simple text to client.

同时getHtml(renderProps)生成 html reactrenderToString()<RouterContext {...renderProps} /> .

我想以某种方式路由到错误组件,该组件将可以使用路由器上下文(或其他方式)访问错误代码,以便它显示适当的错误。

有什么想法吗?

最佳答案

我在服务器端渲染上找到了 404 状态的解决方案,

像这样配置路由:

<Route component={Index} path="/">
  <IndexRoute component={Home} />
  <Route component={Chart} path="chart" />
  <Route component={Login} path="login" />
  <Route component={Error} path="*" notFound />
</Route>

并设置快速路线如下:

app.use((req, res, next) => {
  const location = createLocation(req.url);
  const css = [];
  match({ routes, location }, (err, redirectLocation, renderProps) => {
    if (err) {
      //500 internal error
      return next(err);
    }
    if(redirectLocation){
      //react-router redirect, no problems here
      return res.redirect(redirectLocation.path + redirectLocation.query);
    }
    if (!renderProps){
      //404 not found
      let error = new Error();
      error.message = "Not Found";
      error.status = 404;
      return next(err);
    }

    const notFound = renderProps.routes.filter((route) => route.notFound).length > 0;
    res.status(notFound ? 404 : 200);

    res.end(getHtml(renderProps));
  }
}

关于javascript - React Router 服务器端的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613853/

相关文章:

node.js - 无法访问中间件内 app.use() 的 req.params

javascript - 如何在 expressJS 中保持不断变化的语言状态

reactjs - 错误 : Cannot find module '\react-scripts\bin\react-scripts.js'

node.js - 离线安装 webpack

javascript - 如何使用帮助数据变量获取键的值?

node.js - Sequelize 支持 SQL Server View 吗?

javascript - Pinterest 板仅在页面重新加载时有效

javascript - 超时后组件路由器的状态

javascript - 在不活动时结束 Zopim 聊天

javascript - 始终滚动 div 元素而不是页面本身