React-router not matching query string

1.3k views Asked by At

My routes are defined as follows:

 <Router history={browserHistory}>
   <Route path="/" component={App}>
     <Route path="experiments">
       <IndexRoute component={Experiments} />
     </Route>
     <Route path="*" component={NoMatch}/>
   </Route>
 </Router>

When I visit /experiments, things work as expected and the Experiments component is rendered. However, when I manually enter a URL with query parameters, example: /experiments?offset=50, the route doesn't match!

But when I navigate using <Link to={{ pathname='/experiments', query={offset:50} }} />, things work as expected. The Experiments component is rendered and this.props.location.query.offset is set to 50.

How do I get the Route to match when a URL with query string is entered manually (or copy-pasted)?

It seems route should match automatically url-with-query-‌​string-not-matching-‌​react-router-route, but it doesn't seem to be working for me.

Edit: I narrowed down the problem to the catch-all route path="*". When I remove this route, everything works (e.g. when I visit /experiments?offset=50). But no routes are matched when the catch-all Route is present, even though it is at the bottom of the precedence list.

2

There are 2 answers

1
Shubham Khatri On

You need to make use of historyApiFallback with history={browserHistory} to load your route when you manually enter it.

what historyApiFallback does, is make it so your server returns index.html for whatever URL you try to access and since your routes are then configured with respect to index.html so you can access any of the route url directly

In you webpack add

devServer: {
    historyApiFallback: true;
}
0
saiprashanth On

Ok, turns out this was an entirely unrelated issue. I was using redux-auth which was causing a redirect to the wrong URL pathname. This was happening after the react-router did its parsing and route matching. Once I fixed that, route matching worked perfectly. I was able to parse the query string from a URL like /experiments?offset=50 using the Route config in my question above.