LoginSignup
7

More than 5 years have passed since last update.

RailsでCORSのAccess-Control-Expose-Headersを設定する

Last updated at Posted at 2018-07-08

問題

RailsとReactを使ってアプリを作っているのですが、ローカル環境で別々のサーバを立ててaxiosでRailsのAPIにアクセスしたところレスポンスのheadersが空でした。

解決方法

以下に書いてありました。

config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins Rails.application.config.x.cors_allowed_origins

    resource '*',
             headers: :any,
             expose: ['access-token', 'uid'], # 追加
             methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

expose: ['access-token', 'uid']の部分を追加したところ、適切にheadersが返ってくるようになりました。
exposeの配列の中身はクライアント側で受け取りたいheadersになります。

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
7