Rails 5 の API モードのイニシャライザーで CORS に対応する

  • 26
    いいね
  • 0
    コメント
この記事は最終更新日から1年以上が経過しています。

Rails 5 のプロジェクトを API モードで生成すると CORS 対応するためのイニシャライザーが含まれている。今回はそのイニシャライザーで CORS 対応する方法をメモっとく。

API モードでプロジェクトを生成する

API モードの Rails プロジェクトを生成する。サンプルプロジェクトは本を登録できる本棚プロジェクト。

$ rails new bookshelf --api
$ cd bookshelf

rack-cors gem をインストールする

Gemfile の rack-cors gem を有効にする。

--- a/Gemfile
+++ b/Gemfile
@@ -18,7 +18,7 @@
 gem 'puma', '~> 3.0'
 # gem 'capistrano-rails', group: :development

 # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
-# gem 'rack-cors'
+gem 'rack-cors'

 group :development, :test do
   # Call 'byebug' anywhere in the code to stop execution and get a debugger console 

rack-cors gem をインストールする。

$ bundle

cors.rb を設定する

config/initializers/cors.rb の設定を有効にする。今回は origins* を設定して、全てのオリジンからのアクセスを許可している。本番運用するときは適切に設定してほしい。

--- a/config/initializers/cors.rb
+++ b/config/initializers/cors.rb
@@ -5,12 +5,12 @@

 # Read more: https://github.com/cyu/rack-cors

-# Rails.application.config.middleware.insert_before 0, Rack::Cors do
-#   allow do
-#     origins 'example.com'
-#
-#     resource '*',
-#       headers: :any,
-#       methods: [:get, :post, :put, :patch, :delete, :options, :head]
-#   end
-# end
+Rails.application.config.middleware.insert_before 0, Rack::Cors do
+  allow do
+    origins '*'
+
+    resource '*',
+      headers: :any,
+      methods: [:get, :post, :put, :patch, :delete, :options, :head]
+  end
+end

API を Scaffold 機能で生成する

動作検証用に API を Scaffold 機能で生成する。サンプル API は本を登録できる API。

$ rails g scaffold book title:string
$ rails db:migrate

Rails サーバーを起動して動作検証する

Rails サーバーを起動する。

$ rails s

適当な SSL 接続ではない Web サイト rubyonrails.org などにアクセスして、Chrome のデベロッパーツールの Network と Console を開いて下記の JavaScript を実行する。

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/books');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send('{ "title": "JavaScript: The Definitive Guide, 6th Edition" }');

OPTIONS メソッドのプリフライトリクエストと POST メソッドのリクエストの2つのリクエストが送信される。それぞれ 200 OK201 Created というステータスコードが返ってくれば正常に動作している。