The minimun requered settings to change rails app to api

Premise

I use Ruby on Rails 5.
Now I try to change the rails only app to api, because of converting the view (view of MVC) to React.js.
I used GraphiQL to make rails api.

I would introduce how settings you need for rails api.

But I don’t mention about following:

  • Implementation of GraphQL
  • React.js

Change

Using GraphQL

Although I mentioned not to introduce about the Implementation of GraohQL, but I explain the only necessary part.

Prepare a query what you post to GraphQL api to get some value.
I prepare following:

# query on GraphiQL
query {
  genreGroups {
    id
    booksGenreName
  }
}

The form which I post actually is like this.

  • Method: post
  • Header: Content-Type: application/json
# request body
{
    "query": "query { genreGroups{ id booksGenreName } }"
}

Be careful the query which is used at GraphiQL is sended as the string value of ‘query’ key.
It is meaningless to parse value of GraphiQL into JSON simply.

Correspond to CORS

You must correspond to CORS (Cross-Origin Resource Sharing) even if you use API and React.js in the same server.
Because you must separate their port.

I start rails api to the port of 3001 and the view of React.js to the port of 3000.

rails s -p 3001

The ‘rack-cors’ gem is used to correspond to CORS.

# Gemfile
gem 'rack-cors'

Next, set an authentication at application.rb.
I use about the same of the public example.

# application.rb
module MyApp
  class Application < Rails::Application
    config.load_defaults 5.2

    # Additional lines start
    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
          headers: :any,
          methods: [:post]
      end
    end
    # Additional lines end

  end
end

Setting of protect_from_forgery

Add following to application_controller.rb.

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session # Additional line
end

Settings is complete!

If you need, test the api with Postman.

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です