web-dev-qa-db-ja.com

Create React AppユーティリティでCORSを有効にする

私は[〜#〜] cors [〜#〜]ノードモジュールを使用する必要がありますReact create-react-appユーティリティ。

そのユーティリティなので、内部を調整して[〜#〜] cors [〜#〜]を構成済みの[〜#〜] express [〜#〜]に注入することはできません。 =モジュール。

どうすればこれを達成できますか?

11
Swapnil Kadu

開発にこれが必要で、reactアプリからAPIにアクセスしたいが、このようなエラーが発生する場合-

Failed to load http://localhost:8180/tables: 
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8180'
that is not equal to the supplied Origin. Origin 'http://localhost:3000' is
therefore not allowed access. Have the server send the header with a valid
value, or, if an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.

その後、create-react-appサーバーを使用して、リクエストをAPIサーバーに簡単にプロキシできます。

create-react-appは、webpack開発サーバーを使用して、reactアプリを提供します。

したがって、リアクションアプリがhttp://localhost:3000から提供されていて、接続先のAPIがhttp://localhost:8180/tablesにある場合は、proxy値をリアクションアプリのpackage.jsonファイルに追加するだけです。この-

    proxy: "http://localhost:8180",

次に、あなたの反応アプリからあなたのようなAPIを呼び出します

fetch('/tables').then(....)

リクエストはcreate-react-appサーバーに送信され、APIサーバーに送信されて結果が返されます。

詳細はこちら Proxying API Requests in Development

12
Dave Pile