6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Corsicaを使ってPhoenix/PlugでCORSを秒で設定する

6
Posted at

Phoenixの開発をしていていつもCORSの設定方法をググっていたのですが、
よさそうなライブラリがあったのでメモ :sparkles:

使い方

  1. mix.exs に依存を追加

    mix.exs

defp deps do
[
{:phoenix, "~> 1.5.9"},
...
{:corsica, "~> 1.0"} # 追加 
]
end
```

  1. mix deps.get

  2. lib/<appname>_web/endpoint.ex に設定を追加

    lib/myapp_web/endpoint.ex.exs

...
plug Corsica, origins: "*"
plug MyApp.Router
```

  1. 確認

$ curl -H "Origin: http://localhost" -I http://localhost:4000
HTTP/1.1 200 OK
access-control-allow-origin: *


んー楽だ

# その他の機能

##  他のヘッダーの設定

`Corsica` がサポートしているヘッダーは以下のようです ※`()` はoptionsのキー

- `Access-Control-Allow-Origin`(`:origins`)
- `Access-Control-Allow-Methods`(`:allow_methods `)
- `Access-Control-Allow-Headers`(`:allow_headers `)
- `Access-Control-Allow-Credentials`(`: allow_credentials `)
- `Access-Control-Expose-Headers`(`:expose_headers`)
- `Access-Control-Max-Age`(`:max_age `)

```elixir
plug Corsica, origins: "*", allow_methods: ["POST"], ...

特定のリソースごとに設定を変える

Corsica.Router を使うことで、リソースごとに細かい設定が可能なようです

defmodule MyApp.CORS do
  use Corsica.Router,
    origins: ["http://foo.com", "http://bar.com"],
    allow_credentials: true,
    max_age: 600

  resource "/*"

  # We can override single settings as well.
  resource "/public/*", allow_credentials: false
end
lib/myapp_web/endpoint.ex.exs
  plug MyApp.CORS
  plug MyApp.Router

注意点

common issues に書いてあるとおり、 CorsicaはCORS的に正しいリクエストでないと access-control-allow-origin などのヘッダを返さないようです。
例えば origins: "http://foo.com" とした場合は リクエストのOriginヘッダーが http://foo.com である必要があります

6
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
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?