react-router 如何使用 redirectLocation 或 301 或 302 状态

ind*_*dex 9 javascript http-status-code-301 express reactjs react-router

我们即将在 reactjs 中部署我们的站点,我们已经(重新)移动了一个 url,但将其合并到了我们的主页中,因此/[product]/menu我们将其合并到/[product]. 现在他们说我应该用 301 for 响应/[product]/menu并将其重定向到/[product],我该如何完成这个以及其他一些页面?

如何使用 react-router 设置 301 重定向?我在哪里设置哪些页面需要重定向到哪些其他页面?我现在有这样的设置:

app.get('*', (req, res) => {
  // routes is our object of React routes defined above
  match({ routes, location: req.url }, (err, redirectLocation, props) => {
    console.log(redirectLocation);
    if (err) { // something went badly wrong, so 500 with a message
      res.status(500).send(err.message);

    // HERE: HOW DO I USE THIS?
    } else if (redirectLocation) { // we matched a ReactRouter redirect, so redirect from the server
      console.log('301/302 yeah!');
      res.redirect(301, redirectLocation.pathname + redirectLocation.search);

...
Run Code Online (Sandbox Code Playgroud)

我也使用 reactjs 和 express。

编辑添加的路由配置。

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/products',
    component: ProductsComponent,
    name: 'products'
  }, {
    path: '/:slug',
    component: ProductComponent,
    name: 'product'
  }]
}
Run Code Online (Sandbox Code Playgroud)

以防万一。在此处添加答案:

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/products',
    component: ProductsComponent,
    name: 'products'
  }, {
    path: '/:slug',
    component: ProductComponent,
    name: 'product'
  }, { 
    path: '/:product/menu', onEnter(nextState, replace) { replace(`/${nextState.params.product}`) }
  }, {
    path: '/oldlink/:testId', onEnter(nextState, replace) { replace({pathname: `http://newsite.com/oldlink/some/${nextState.params.testId}`}) }
  }]
}
Run Code Online (Sandbox Code Playgroud)

Dam*_*oux 3

在路由声明中,使用<Redirect>. 示例在这里

  • @index 请务必在重定向标记中包含 301 状态。默认为 302。 EG &lt;Redirect status={301} from="..." to="..." /&gt; (3认同)