onedkr
onedkr

Reputation: 3386

Routes on server & client side - React.js & Node.js

I try to really understand how routes work with react-router on my react application and express on my node.js server.

React-router code :

import ..
import { Router, Route, IndexRoute, hashHistory, IndexRedirect, Redirect } from "react-router";

render(
  <Router history={hashHistory}>
    <Redirect from="/" to="/index"/>
    <Route path="/" component={App}>
        <IndexRoute component={NavBarTop} />
        <IndexRoute component={NavFilter} />
        <Route path="/index" component={Tickets} />
        <Route path="/ticket/:id" component={TicketInformations} />
        <IndexRoute component={InterventionsList} />
    </Route>
  </Router>,
document.getElementById('container'));

My server routing:

app.use('/', express.static(path.join(__dirname, '../client/')), function(res, eq) {
});

app.get('/test', function (req, res) {
  console.log("test");
  var data = getTickets(); // return a JSON
  res.end( data );
});

my react routing works perfectly, however I want to make a AJAX call to fill my components. For this I try to get a JSON from my node server. However the path 'test' doesn't work. My console.log is not called.

I don't know why, I probably didn't understantd how it really works. How can I create easily webservice to prepare my AJAX call ?

Upvotes: 2

Views: 4566

Answers (1)

Abu Md. Maruf Sarker
Abu Md. Maruf Sarker

Reputation: 66

ReactJS applications are single-page applications (SPA) and, generally they are served from root ("/") of your express.js server. But, unlike any static webpage, a SPA don't call server for every route change, rather depends on virtual routes and it's own client-side route handlers. (if you wonder, why SPAs don't refresh page, this is the reason behind, somewhat). If a SPA uses any routes defined in its client-side route handlers, the express will always see it as the root route "/" and do nothing, actually it won't know anything, as browser won't make any request.

React-Router provides these virtual routes to ReactJS app.

In your code, when your React app goes from "/" to "/index" or any other routes defined using React-Router, it does not request express server for anything, rather everything is done over client-side/browser. That's why, even if you had a route defined as "/test" for ReactJS, it would not call server-side for anything.

(by the way, these virtual routes will also be used by React over server-side, if and only if you're using React's server-side rendering. But, express will not know about these. Express will always behave the same, whether you use client-side rendering or server-side rendering.)

Now, lastly, if you want your express route "/test" to be called, you'll have to make a fetch request towards the route, thus the route will be called. (have a look at isomorphic-fetch, if wondering which library to use)

Hope these come handy

Upvotes: 5

Related Questions