LoginSignup
3
2

More than 5 years have passed since last update.

CORS紹介

Last updated at Posted at 2016-11-14
1 / 11

背景

  • 現在のWebブラウザでは、same-origin policy(同一生成元ポリシー)が適用される

CORSとは

  • Cross-Origin Resource Sharingの略称
  • CORSでは、データのアクセスを許可できるWebサイトに対してはOriginを越えたアクセスを可能になる

HTTP requests

  • Origin ヘッダーを含んでいる

Origin: http://localhost:9191

HTTP responses

以下のヘッダーを含んでいる

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Max-Age

Access-Control-Allow-Origin: http://localhost:9191
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT
Access-Control-Max-Age: 1728000

example


クライアント側の対応(javascript)

function request(){
      $.ajax({
        type: "POST",
        url: "http://localhost:9292/index",
        dataType: 'json',
        success: function (data){
          alert("success");
        },
        error: function (data){
          alert("error");
        }
      })
    }

サーバー側に、CORSを対応していない場合

  • No 'Access-Control-Allow-Origin' header is present on the requested resourceエラーが出た
  • サーバー側からレスポンスが戻ったが、ブラウザより禁止された

サーバー側の対応(例:ruby)

  • rackの場合は、以下のコードをconfig.ruに追加
use Rack::Cors do
  allow do
    origins 'localhost:9191'
    resource '*', headers: :any, methods: [:get, :post, :options, :put]
  end
end
  • レスポンスが200戻った

aws s3に、CORS対応

  • バケットのプロパティ -> Permissions -> Edit CORS Configuration
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

参照

3
2
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
3
2