【问题标题】:ReactJS fetching API - having CORS errorReactJS 获取 API - 出现 CORS 错误
【发布时间】:2019-01-23 03:37:33
【问题描述】:

从 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 请求。工作正常。

【问题讨论】:

    标签: reactjs cors fetch


    【解决方案1】:

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

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

    解决方案:

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

    Chrome - 无安全性 (Windows) 示例

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

    【讨论】:

    • 我找到了解决方案。我应该代理我的后端:)
    猜你喜欢
    • 2020-08-24
    • 2018-06-09
    • 2022-11-07
    • 2021-04-21
    • 2018-06-23
    • 2021-01-24
    • 2020-01-14
    • 2019-02-10
    • 2018-01-12
    相关资源
    最近更新 更多