index index - 6 months ago 171
Javascript Question

react-router how do I use redirectLocation or the 301 or 302 status

We are about to deploy our site in reactjs and we have (re)moved one url but merged it in our main page so from

/[product]/menu
we merged it to
/[product]
. Now they said I should respond with 301 for
/[product]/menu
and redirect it to
/[product]
, how do I accomplish that and some other pages as well?

How do I setup 301 redirects using react-router? Where do I setup what pages needs to be redirected to what other pages? I have my setup like this right now:

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);

...


I use reactjs and express as well.

Edit Added route config.

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


Just in case. Added answer here:

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

Answer

In the routes declaration, use <Redirect>. Example Here