Home > Software design >  Proper way to connect to backend using React and RESTful Web Services
Proper way to connect to backend using React and RESTful Web Services

Time:10-18

I have a SPA application using reactJS for the front end, and Ruby on Rails for the backend; all navigation is routed through the react router. My question is, how do I access my model using react?

I think the proper way would be to expose the functionality of the model through a REST API. The problem is that the model's REST API is routed to return a page and not a JSON object. For example, /posts/index will return the posts index page, NOT the list of posts. What I need to do is to call another request when the user enters "/post/index", i.e., call a request from the index component, to retrieve the posts and return them as a JSON object. My workflow would be something like this: User navigates to index page > React sends HTTP request to access server.

One potential solution is maybe to implement a second controller, called say posts_react_controller, and then have this controller return JSON data and expose it via the appropriate url. Is this best practice?

Thank you!

CodePudding user response:

Rails servers can be run in API-only mode, this is exactly what you need. You should be able to continue using your existing controllers and have them serve JSON instead of HTML.

Another option is to append a file type to your requests (/post/index.json), and modify your controller to handle different request formats:

class UsersController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render xml: @users }
      format.json { render json: @users }
    end
  end
end

With either route you'll probably want to use a gem like jbuilder which gives you a DSL for building JSON responses, similar to how you use ERB to generate HTML.

  • Related