Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony and React router, no route found

I am using Symfony3 and I am creating a bundle using React.js using itself react-router.

The issue is when I use the routing in react, if I reload the page the symfony routing module send 'No Route Found"

My routes are /admin for the index page and /admin/data for the next page.

When I load the page /admin everything is good, I click on the link to go to /admin/data, everything works, react send me dynamically on it, but now when I refresh (F5) the page /admin/data, Symfony intercept it and try to find the routing in its code and redirect to /404 "No Route Found".

I know on AngularJs, the framework is using ancors Path "localhost://admin/#/data", which seems easier to manage but react-router use "localhost://admin/data"

My symfony routing:

admin:
  path: /admin
  defaults: { _controller: BiBundle:Admin:default }

My React routing:

import { Router, browserHistory } from "react-router";

<Router history={browserHistory}>
  <Route path="/admin" component={App}>
    <IndexRoute components={{content: DashboardPage}} />
    <Route path="data/list"
      components={{content: DataListPage}} />
    <Route path="*"
      components={{content: _ => <h1>Page not found.</h1>}} />
  </Route>
</Router>

My link on /admin page:

<Link to={'/admin/data/list'}>Data</Link>

I was thinking to modify my .htaccess to redirect all /admin/* to /admin but seems overkill for that issue.

I am using Apache2 server too.

EDIT

I have replaced browserHistory by hashHistory

import { Router, hashHistory } from "react-router";

<Router history={hashHistory}>
  <Route path="/" component={App}>
    <IndexRoute components={{content: DashboardPage}} />
    <Route path="data/list"
      components={{content: DataListPage}} />
    <Route path="*"
      components={{content: _ => <h1>Page not found.</h1>}} />
  </Route>
</Router>

It had the result to change my path as it is used in AngularJs (or close enough), so now I have /admin#/ and /admin#/data/list, so symfony always catch /admin and react-router catch #/ or #/admin/data

What do you think ? Is it the good methodology ?

like image 898
Cifren Avatar asked Mar 17 '16 10:03

Cifren


1 Answers

To make your AJAX routing accessible from url directly (i.e. typing /admin/data in browser URL) without being redirected server-side, you need to make your base route (the Symfony route that renders your React application) taking a parameter that will represents your AJAX routing.

To do this, the parameter must allow slashes, example:

admin:
    path: /admin/{reactRouting}
    defaults: { _controller: BiBundle:Admin:default, reactRouting: null }
    requirements:
        reactRouting: ".+"

For a more complex routing, you should look at the FOSJsRoutingBundle that could help you.

like image 112
chalasr Avatar answered Sep 23 '22 17:09

chalasr