Reputation: 3803
I am interested about React.js for server side rendering for my web service, but I encounter one problem trying to port from my web service developed using Express.js. Currently, my web service is serving 2 platform
My current architecture is all my client side are connected to my server using JSON. So, my client will send a HTTP GET/POST request to my server and I will return JSON back. My server doesnt server HTML page.
Below, are examples of my endpoints APIS using REST:
How should I change my server side to include React? Since React uses server side rendering instead of communicating using JSON?
My current Angular.js project, I placed them into a public folder and it serves as static files.
Possible solutions:
UPDATE 1
Another possible solutions
res.format({
'text/html': function() {
var html = React.renderToString(React.createElement(BooksPage, {books: books}));
res.render('main-layout', {
html: html,
data: JSON.stringify({books:books})
});
},
'application/json': function() {
res.send({
book: books
})
}
})
is to use Express.js content negotiation (res.format), doing so i keep the same route for handline HTML and JSON?
Upvotes: 1
Views: 784
Reputation: 86240
You have your api routes, and you have your page routes. The user doesn't go to http://example.com/api/books to see a list of books, they go to something like http://example.com/books/ to see the books page.
When you get a request for a page like /books/, you serve html. Your api can still be used on the client.
The simplest way to do this is make very lean controllers, and keep most of the logic in plain functions (example with promises, but not important).
function getBooks(){ return /* database thing returns promise */ };
app.get('/api/books', function(req, res){
getBooks().then(function(books){ res.send(books); });
});
app.get('/books/', function(req, res){
getBooks().then(function(books){
var html = React.renderToString(React.createElement(BooksPage, {books: books}));
res.render('main-layout', {
html: html,
data: JSON.stringify({books:books})
});
});
});
Let's say your main-layout template ends up producing this:
<html><head></head>
<body>
<div id="root">
<!-- output of renderToString -->
<div data-reactid="0">...</div>
</div>
<script>
/* output of the JSON.stringify */
var __initial_data = [{"id": ...}];
</script>
<script src="client-side-code-bundle.js"></script>
</body>
</html>
You pick up the rendering on the client using the same data as the server used:
React.render(React.createElement(BooksPage, __initial_data));
Your event listeners are bound, and you go from there.
Upvotes: 2