ReactJS提取API-发生CORS错误

时间:2018-08-16 08:19:26

标签: reactjs cors fetch

从ReactJS应用发送请求:

fetch(http://my-api-domain, {
        method: 'GET',
        mode: 'cors', //tried no-cors and same-origin
        headers: {
            'X-Auth-Token': auth_token' // custom-header
        }
    }).then(response => console.log(response))
        .then(data => {
            console.log(data);
        }
    });

package.json文件具有"proxy": "http://my-api-domain/"

然后我在浏览器(firefox)上遇到此错误:

- Cross-Origin Request Blocked: (Reason: missing token ‘x-auth-token’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
- Cross-Origin Request Blocked: (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
- Cross-Origin Request Blocked: (Reason: CORS request did not succeed).

PS:API服务器配置很好。我已经在Postman上测试了我的API。发送标头为key: X-Auth-Token; value: [token]的GET请求。工作良好。

1 个答案:

答案 0 :(得分:0)

这在邮递员中有效,因为它忽略了CORS请求。

如果您设置“ no-cors”模式,出于安全考虑,浏览器仍然可以忽略它。 Chrome浏览器肯定会忽略此标志并返回错误。

解决方案:

  • 如果是您的api,请在api上将您的IP列入白名单
  • 设置反向代理(例如Nginx),它将为您添加允许来源标头。然后,您将向RP发出请求,它将返回带有为您附加的Allow-Origin标头的响应
  • 在本地设置.php或node.js代理端点,这将与RP相同
  • 以非安全模式启动浏览器。

Chrome-不安全(Windows)示例

"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security