LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】APIにCORS設定する手順

Last updated at Posted at 2021-07-19

はじめに

RailsをAPIサーバとして使用することが多いと思います。
その場合ビュー(V)の役割であるReact等を用いたフロントエンド側サーバ(Node.js)から、Railsにリクエストを投げることになりますが、その際に避けて通れないRails側でのCORS設定の手順を自分用にまとめました。

手順

gemfileに "rack-cors"を記述し、$ bundle install を実行

# 以下の文をGemfileに追記
gem 'rack-cors'

→bundle installを実行すると、config/initialize配下にcors.rbファイルが生成されます。

作成されたcors.rbに、以下のコードを記述

(ⅰ) 全てのオリジンを許可する場合

cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :patch, :put]
    credentials: true # cokkieを利用する場合のみ記述
  end
end

(ⅱ) 特定のオリジンのみ許可する場合 (例. 'localhost:3000'のみを許可)

cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000' # 許可させたいオリジン名を記述 (これは'localhost:3000'の場合の例)
    resource '*', headers: :any, methods: [:get, :post, :patch, :put]
    credentials: true # cokkieを利用する場合のみ記述
  end
end
0
0
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
0
0