【问题标题】:I am trying to call a 3rd party api and it is giving me a CORS error我正在尝试调用第 3 方 api,但它给了我一个 CORS 错误
【发布时间】:2020-09-02 21:23:28
【问题描述】:
const https = require('https');

export async function main(event, callback) {
    const options = {
        method: 'GET',
        host: 'https://api.challonge.com/v1/',
        headers: {
            'Access-Control-Allow-Methods': 'GET',
            "api_key": "THE_KEY",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": true
        }
    };
    var dataString = " ";

    const response = await new Promise((resolve, reject) => {
        const req = https.get(options, function (response) {
            response.on('data', chunk => {
                dataString += chunk;
            });
            response.on('end', () => {
                resolve({
                    statusCode: 200,
                    headers: {
                        "Access-Control-Allow-Origin": "*"
                    },
                    body: JSON.stringify((dataString))
                });
            });
        });
        req.on('error', (e) => {
            reject({
                statusCode: 500,
                headers: {
                    "Access-Control-Allow-Origin": "*"
                },
                body: e.message
            });
        });
    });
    return response;
};

这是 lambda 函数 ^

getChallongeTournaments:
    handler: getChallongeTournaments.main
    events:
      - http:
          path: tournaments/
          method: get
          cors: true
          authorizer: aws_iam

我的 serverless.yml

// in a useEffect
function getChallongeTournaments(){
     return API.get("byoc_users", '/tournaments.json');
    }
    async function onLoaded() {
      try {
       const testChallonge = await getChallongeTournaments();

^ API 调用

根据 challonge 文档,这应该会收到“检索使用您的帐户创建的一组锦标赛”。并且创建了一个。

这是我收到的 CORS 错误:从源“http://localhost:8100”访问 XMLHttpRequest 在“https://m3heucf413.execute-api.us-east-2.amazonaws.com/prod/tournaments.json”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:确实如此没有 HTTP ok 状态。

【问题讨论】:

  • Access-control-allow-credentials 可能不会像您认为的那样做,并且会施加奇怪的规则。最常见的错误是 lambda 爆炸从 API 网关服务返回 500 而没有 cors

标签: reactjs amazon-web-services api aws-lambda serverless


【解决方案1】:

当有从域/端口到全新域/端口的请求时,浏览器会引发预检请求和 CORS 标志。如果您这样做是为了测试,您可以通过添加 --disable-web-security 标志在 chrome 中禁用此安全标志。只需创建 chrome 到桌面的快捷方式 > 右键单击​​ > 属性 > 在快捷方式选项卡中 - 目标 > 将 --disable-web-security --user-data-dir="C:\tmpChromeSession" 附加到目标。这将禁用 CORS 检查。

如果您对第 3 方 api 服务器配置具有访问/控制权,您应该做的是在响应中添加必要的响应标头 (Access-Control-Allow-Origin)。如果您无权访问,一种选择是通过 CORS 代理路由请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多