LoginSignup
52
48

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-05-25

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 というステータスコードが返ってくれば正常に動作している。

52
48
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
48