LoginSignup
0
0

More than 1 year has passed since last update.

【備忘録】RailsAPIとフロントをつなぐ際のCORSの対処

Last updated at Posted at 2023-04-21

前書き

Railsで作成したAPIとVueをつないでみようとした時のこと。

フロント側からaxiosでAPIを叩いてみたけれど、データが取れないでいた。

ブラウザの開発者ツールを開くと、なにやらCORS云々でデータが取れないのだとか。

以下に、RailsAPIとVueをつなぐ際のCORSに関する対処を備忘録として書いておく。

対処方法①

Gemfileに以下を記述し、bundle installする。

Gemfile
    gem 'rack-cors'


config/initializers/cors.rbから許可する相手やメソッドなどを設定することができる。

config/initializers/cors.rb
    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins "localhost:8080"
    
        resource "*",
          headers: :any,
          methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end

対処方法②

config/application.rbに以下の内容を記述する。

config/application.rb
config.action_dispatch.default_headers = {
      'Access-Control-Allow-Credentials' => 'true',
      'Access-Control-Allow-Origin' => 'http://localhost:8080',
      'Access-Control-Request-Method' => ['GET', 'POST', ……]  # '*'とすれば、全てのメソッドを指定
    }

終わりに

今回、CORSに関する躓きに気づくまでなかなか時間がかかってしまいました。

ブラウザの開発者ツールをしっかり活用していく癖をつけられるようにしていければと思います:D

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