web-dev-qa-db-ja.com

ローカルホストからのオリジンでのCORSの問題が原因でリクエストが失敗する

SOや、これについて「答え」で話しているさまざまなブログで、何十もの質問を見てきましたが、まったく役に立ちませんでした。

ローカルマシン(Ubuntu 16.04)にReact.jsアプリがあります。ローカルでは、npm startを実行してテストしようとすると、ブラウザが http:// localhost:30 に開きます。

あるページで、共有ホスティングサーバー上にあるPHP apiにアクセスしようとしています。

ChromeとFirefoxはどちらも、サーバーにAccess-Control-Allow-Orginがないために失敗すると言っています。

正確なメッセージ:

Failed to load http://---/api/v1/categories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.com:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
localhost.com/:1 Uncaught (in promise) TypeError: Failed to fetch

ただし、PHPサーバーのエントリポイントには次のものがあります。

header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");

これが、reactアプリでAPI呼び出しを行う場所です。

 componentDidMount() {

  var options = {
    method: 'get',
    headers: {
        "Access-Control-Request-Headers": "*",
        "Access-Control-Request-Method": "*"
    },
  }

  // I have since removed the headers from the options as advised in the comments 
  fetch('http://---/api/v1/categories', options)
  .then(results => {
    return results.json();
  }).then(data => {
    let categories = data.map((category) => {
      return(
        // edited out
      )
    })
    this.setState({categories: categories});
  })
 }
}

ChromeとFirefoxの両方でこれを試しました。また、サーバーをローカルホストからエイリアスしようとしました。アクセスを取得するno-corsアプローチを試しましたが、もちろん、すべてを壊します。fetchリクエストと一緒にヘッダーを渡す場合と渡さない場合で試しました。

[〜#〜]更新[〜#〜]

this Chrome plugin 。これは回避策だと思います。ここにコーディングの答えがあるかどうか知りたいです。

6

私はアホです。

OriginのつづりがOrginと間違っていました。

このタイプミスは、私のプロジェクトに3年近く存在しています。クロスドメインアクセスを使用する必要があったのはこれが初めてでした。

3
header("Access-Control-Allow-Methods: *");

する必要があります:

header("Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH");

...そしてあなたが受け入れるつもりの他の方法。

0
Dai