LoginSignup
0
0

More than 1 year has passed since last update.

[解決]Access to XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Posted at

結論

RailsAPIとVue間でデータを共有しようとしたところエラー。API側のCORS設定がうまく行っていなかったことが原因だった。

詳しく

エラーのコード

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

CORSが正常に機能したコード

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:8080', 'http://localhost:3002/v1/blogs/'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

originを全て受け入れる(*)にすると、CORSのセキュリティ的にエラーが出るようになっているらしい。だから、クライアント側のoriginを明記すると、CORSが機能する。

参考

https://web.dev/cross-origin-resource-sharing/
https://qiita.com/att55/items/2154a8aad8bf1409db2b
https://qiita.com/residenti/items/3a03e5e0268b354284b7

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