【问题标题】:Why do I get a CORS error on API Gateway GET request when the OPTIONS request has statusCode 200?当 OPTIONS 请求的 statusCode 为 200 时,为什么我会在 API Gateway GET 请求中收到 CORS 错误?
【发布时间】:2019-08-03 04:05:36
【问题描述】:

我正在尝试向连接到 lambda 函数的 AWS API Gateway 端点发出 GET HTTP 请求。

端点和 lambda 函数在使用 postman 测试时照常工作,这是合乎逻辑的,因为 postman 不使用 CORS。

但是,在 chrome 上测试 firefox 时,我收到以下错误:

火狐:

跨域请求被阻止:同源策略不允许读取 [url] 处的远程资源(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

铬:

访问 [url] 从源“http://localhost:8080”获取已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

但是,如果我查看 CORS Preflight 请求的响应,我会看到存在“Access-Control-Allow-Origin”:

HTTP/2.0 200 正常
日期:格林威治标准时间 2019 年 3 月 12 日星期二 15:22:57
内容类型:应用程序/json
内容长度:0
x-amzn-requestid:[x-amzn-requestid]
access-control-allow-origin:*
访问控制允许标头:内容类型、X-Amz-Date、授权、X-Api-Key、X-Amz-Security-Token
x-amz-apigw-id:[x-amz-apigw-id]
访问控制允许方法:GET,OPTIONS
X-Firefox-Spdy:h2

我尝试使用 fetchrequest 包来处理我的请求,并使用以下代码(我将 request 调用包装在 Promise 中,以使用像fetch 调用):

const getPolicy = (baseUrl, bucketNameTranscribe, fileName, apiKey) => (
    new Promise((resolve, reject) => {
        request({
             url: `${baseUrl}?bucketName=${bucketNameTranscribe}&key=${fileName}`,
             method: "GET",
             headers: {
                 "x-api-key": apiKey
             }
        }, ((error, response) => {
            if (error) {
                reject(error);
            } else if (response.statusCode === 200) {
                resolve(JSON.parse(response.body));
            } else {
                reject(response);
            }
        });
    })
);

const upload = async() {
    const {
        policyUrl,
        bucketNameTranscribe,
        apiKey
    } = awsConfig;
    const fileName = `${Date.now()}.mp3`;
    const req = new Request(
        `${policyUrl}?bucketName=${bucketNameTranscribe}&key=${fileName}`,
         {       
             method: "GET",
             headers: new Headers({
                 "x-api-key": apiKey
             })
         }
    );

    try {
        const response1 = await fetch(req);
        console.log("fetch", response1);
    } catch (error) {
        console.error("errorFetch", error);
    }

    try {
        const response2 = await getPolicy(policyUrl, bucketNameTranscribe, fileName, apiKey);
        console.log("request", response2);
    } catch (exp) {
        console.error("errorRequest", exp);
    }
}

提前感谢您的帮助

【问题讨论】:

  • content-type: application/json content-length: 0 — 如果没有发送任何内容,您的 OPTIONS 响应不应说它正在发送 JSON。

标签: javascript cors fetch aws-api-gateway requestjs


【解决方案1】:

错误信息说:

请求的资源上不存在“Access-Control-Allow-Origin”标头。

实际资源中缺少 Access-Control-Allow-Origin 标头,而不是对预检 OPTIONS 请求的响应。

它需要在两者上。

【讨论】:

  • 就是这样,非常感谢!我遵循了这个guide,在该方法上启用了CORS并且它起作用了。
猜你喜欢
  • 2019-07-10
  • 2017-06-18
  • 2020-12-15
  • 2013-08-11
  • 2018-04-25
相关资源
最近更新 更多