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

【React】CORSエラーの備忘録

Posted at

Reactでシステムのメンテナンスをしていたところ、以下のようなエラーが出た。

Access to XMLHttpRequest at 'http://127.0.0.1:3000/ファイル名' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

どうやらCORSポリシーに違反しているのでリクエストをブロックするとのことらしい。

ブラウザ(フロント側)からバックエンドサーバーにリクエストを送った時に起こるエラーでCORSポリシーによってアクセスが出来なくなってしまった。

ここからは私が実際に行ったやり方なので参考程度に見て欲しいです。(自信ない)

Access-Control-Allow-Originヘッダーを追加

header('Access-Control-Allow-Origin: http://127.0.0.1:3000');

今回は記事を見ても上手く動かなかったのでhttp://127.0.0.1:3000 をヘッダーに追加。

*を使ってすべてのオリジンからアクセスできるようにすることもできますが、非公開APIやセキュリティの面でも危ないので使うときは気を付けましょう

Access-Control-Allow-Originとは

Access-Control-Allow-OriginとはHTTPヘッダの項目の一つで、送信するコンテンツが他のサーバーとのリソース共有(CORS)を許可されているかを示すもの。

【参考記事】
Access-Control-Allow-Origin 【ACAO】

package.jsonにプロキシ設定を記述する

以下の記事を参考にプロキシ設定
Reactのproxy設定を細かく設定する

   "proxy": {
     "/api": {
       "target": "http://127.0.0.1:3000"
     }
   }

だが、この書き方だとReactではエラーになるらしい。(実際にエラーが出てしまった)
間違っていたらすみません。

書き方を以下に変更したところエラーは出なくなった。

"proxy": "http://127.0.0.1:3000"

CORSがまだちゃんと理解できていないのでしっかり理解できるようにしたい。

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