7
1

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 1 year has passed since last update.

curlでCORSリクエストの再現方法

Posted at

curlでpreflightリクエストを再現するときは、HTTPヘッダに次の3つが最低限必要。(MDN:『Preflight request (プリフライトリクエスト)』より)

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers

例えばローカルにMockAPIなどを建ててCORSの動作確認する場合、次のようなコマンドを実行するとよい。

curl -v -X OPTIONS \
    -H 'Origin:*' \
    -H 'Access-Control-Request-Method: GET' \
    -H 'Access-Control-Request-Headers: content-type' \
    http://localhost/目的のMockAPIのURLなど

なお -v とするのは受送信状況を確認するため。preflightリクエストが成功すると 204 No Content 応答なので何も表示されないため。

このメモの背景

PRISM(stoplightio/prism)Dockerコンテナを使ってリバプロの後ろにMockAPIを建てた時、CORSの動作確認をしようとしたら、次のエラーが出てしまった。

(読みやすいように改行済み)
{
  "type":"https://stoplight.io/prism/errors#NO_METHOD_MATCHED_ERROR",
  "title":"Route resolved, but no method matched",
  "status":405,
  "detail":"The route リクエストしたパス has been matched, but it does not have \"options\" method defined"
}

「あれ? PRISMはCORSをうまくしてくれるんじゃねーんだが?」 と思ったのが調査の始まり。
なお、原因はヘッダOriginがない状態でリクエストしたから。

参考資料

7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?