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

标签 javascript express reactjs react-router http-status-code-301

我们即将在 reactjs 中部署我们的网站,我们已经(重新)移动了一个 url,但将其合并到我们的主页中,因此从 /[product]/menu 我们将其合并到 /[产品]。现在他们说我应该用 301 响应 /[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);

...

我也使用 reactjs 和 express。

编辑添加了路由配置。

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/products',
    component: ProductsComponent,
    name: 'products'
  }, {
    path: '/:slug',
    component: ProductComponent,
    name: 'product'
  }]
}

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

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}`}) }
  }]
}

最佳答案

在路由声明中,使用<Redirect> . Example Here

关于javascript - react-router 如何使用 redirectLocation 或 301 或 302 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37388359/

相关文章:

javascript - JQuery 不附加 html 表单

javascript - 是否有 Node.js 的 XSD 验证器

node.js - ExpressJS : How to mock request handler next function with mocha

javascript - 使用 React 生成动态 PDF

reactjs - typescript 错误: Property 'code' does not exist on type 'KeyboardEvent<HTMLInputElement>'

javascript - 如何将参数传递给 javascript 函数内的 Ruby 'send' 方法?

javascript - 浏览器由于(太重?)JavaScript、 Canvas 渲染而卡住

mysql - 为什么我无法获取查询结果

javascript - express js中的请求参数

javascript - 如何打乱对象数组