I want to create a Rails + React.JS application and I've seen that most of the tutorials on the web mention about REST API. The data I want to be served through JSON
I understand what's a REST API but what I do not understand is how does the frontend gets served to the user?
Do I need to have 2 Rails projects , one for the API , from which we get JSON data (like users etc) and one for the View Layer which will return an HTML with plenty of javascript ?
And what if I create only a simple rails app ( not API), which has controllers for the view-layer (to render html/javascript ) and controllers for json data (which would be " API ") ? Would that be a good practice or not?
All I want to create is an app that: you visit a page, say /users/1 , get the HTML content (which would be mostly referencing scripts and that's it) and another route responsible for json data from which we pull data, let's say /api/users/1.json (which would be a namespace route to match the api folder in controllers).
What you want to do here is to use react-rails. It also allows server side rendering (no REST API).
https://github.com/reactjs/react-rails
Just run gem 'react-rails'
, bundle install
, and rails g react:install
Then you just list components to your application.js file like below and can start using react components from automatically created folder at app/assets/javascripts/components/
//= require react
//= require react_ujs
//= require components
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.