反应路由器服务器端的错误处理

时间:2016-06-03 12:00:44

标签: javascript express reactjs react-router

我正在使用react-router&amp ;;开发同构应用程序express。我在服务器端渲染中使用了反应路由器。我希望有自定义错误页面,它将在服务器端错误,渲染错误或未找到的情况下发送。但我在连接点时遇到了问题。 这是我的路线:

<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)react上生成renderToString() <RouterContext {...renderProps} />的html。

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

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我在服务器端渲染中找到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));
  }
}

答案 1 :(得分:0)

我可能错了,但试一试:

if (!renderProps) {
  //404 not found
  let error = new Error();
  error.message = "Not Found";
  error.status = 404;
  res.status(error.status).end(someErrorHtml); // <- I think you are missing this
  return next(err);
}