Betamee
Betamee

Reputation: 13

How does React server-side rendering deal with RESTful API (react-router+express)?

I've got a problem with react SSR. I use react-router as my app route manager.

In the server side, it may look like this (server.js):

var app = express();
app.get("*",function(req, res ){
     match({routes:AppRoutes, location:req.url},

      function(err, redirectLocation, renderProps){
        if (error) {
          res.send(500, error.message)
        } else if (redirectLocation) {
          res.redirect(302, redirectLocation.pathname + redirectLocation.search)
        } else if (renderProps) {
          res.send(200, renderToString(<RoutingContext {...renderProps} />))
        } else {
          res.send(404, 'Not found')
       }
    });
});

In case react-router consumes all GET routes, if I need RESTful API in the server side, how do I separate it from react-route?

And if I have a component in the frontend:

class Post extends Component{
    componentDidMount(){
       fetch('/api/post')
         .then(function(response){
              //change component state or do other
         })
         .catch(function(err){
             //handle error
         })
    } 
     render(){
      // 
     }
}

How does this component communicate with server by RESTful API?
Can Express provide such RESTful API structure?

app.get("/api/post",function(){
    //do something and response
});

I really dont understand.

Upvotes: 1

Views: 1781

Answers (1)

Jakob Lind
Jakob Lind

Reputation: 1440

Q: "In case react-router consumes all GET routes, if I need RESTful API in the server side, how do I separate it from react-route?"

A: You can listen to API calls with the code you wrote:

app.get("/api/post",function(){
    //do something and response
});

But you have to put it above your other code that listens for "*".

Q: "How does this component communicate with server by RESTful API?"

A: Your components will not do the Ajax call when rendering on the server. The function componentDidMount will not be called on server side.

Upvotes: 2

Related Questions