javascript - 如何让React路由器响应404状态码?

标签 javascript reactjs http-status-code-404 frontend react-router

我以root身份使用react router,并且“/”下的所有请求都定向到react router。当React Router发现url与任何定义的组件不匹配时,它会使用NoMatch组件进行渲染。问题来了,NoMatch 被渲染了,这就是我想要的,但状态代码仍然是 200 而不是 404。当我的 css 或 js 文件放置有错误的 url 时, react 路由器会做同样的事情,它会响应 200 !然后页面告诉我,我的资源内容类型存在一些问题!

那么,我如何使用React Router来处理“/”中的所有内容,并且仍然让它正确处理404错误(以404状态代码响应)?

react 路由器中的代码

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Index}/>
      <Route path="archived" component={App}>
        <IndexRoute component={ArchivedPage}/>
        <Route path="project/:projectId" component={ArchivedDetailPage}/>
      </Route>
      <Route path="*" component={NoMatch}/>
    </Route>
  </Router>
), document.getElementById('app'));

服务器端

  router.use('/', function(req, res, next) {
    res.render('index-react', {
      title: 'some title'
    });
  });

最佳答案

使用react-router 2.0.0你可以这样做:

<Route path="*" component={NoMatch} status={404}/>

编辑:

您需要做的是在路线定义上创建自定义属性,如上面所示(状态)。

当您要在服务器端渲染组件时,请检查此属性并使用此属性的代码发送响应:

routes.js

import React from 'react';
import {IndexRoute, Route} from 'react-router';

import {
    App,
    Home,
    Post,
    NotFound,
} from 'containerComponents';

export default () => {
    return (
    <Route path="/" component={App}>

        <IndexRoute component={Home} />
        <Route path='post/' component={Post} />

        { /* Catch all route */ }
        <Route path="*" component={NotFound} status={404} />

    </Route>
  );
};

服务器.js:

import { match } from 'react-router';
import getRoutes from './routes';
....
app.use((req, res) => {
match({ history, routes: getRoutes(), location: req.originalUrl }, (error, 
        redirectLocation, renderProps) => {
        if (redirectLocation) {
          res.redirect(redirectLocation.pathname + redirectLocation.search);
        } else if (error) {
          console.error('ROUTER ERROR:', error);
          res.status(500);
        } else if (renderProps) {

            const is404 = renderProps.routes.find(r => r.status === 404) !== undefined;
        }
        if (is404) {
          res.status(404).send('Not found');
        } else {
            //Go on and render the freaking component...
        }
    });
});

抱歉……我的解决方案本身无法正常工作,并且我错过了您实际检查此属性并相应渲染的正确代码段。

如您所见,我只是将“未找到”文本发送给客户端,但是,最好从 renderProps 捕获要渲染的组件(在本例中为 NoMatch)并渲染它。

干杯

关于javascript - 如何让React路由器响应404状态码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052604/

相关文章:

javascript - 在 Backbone.JS 中创建不更新 ID

php - Javascript大文件 uploader

reactjs - 此版本不符合 Google Play 64 位要求 React Native 应用程序

javascript - 我应该在 2019 年将我的 JWT 存储在哪里,localStorage 真的不安全吗?

sharepoint-2010 - 如何为 VHD 配置 VMware 工作站

javascript - 如何删除 Phaser 3 中的图像?

javascript - 我正在使用 JavaScript 和 Regex 围绕链接构建对象。需要澄清一下

reactjs - 如何让我的 React Web 应用程序出现在谷歌搜索中?

servlets - web.xml 404重定向到servlet,如何获取原始URI?

Symfony 2 - 加载 Web 调试工具栏时出错 (404 : Not Found)