You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用AWS REST API时遭遇CORS预检请求失败问题求助

解决AWS REST API调用时的CORS错误

遇到的错误信息

Access to fetch at '$(url)' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

前端请求代码

let body = { token: params.token};
const response = await fetch(
  url,
  {
    method: "POST",
    body: JSON.stringify(body),
    headers: { "Content-type": "application/json", "Access-Control-Allow-Origin":"*" },
  }
);
console.log(response);
const myJson = await response.json();
console.log("response-->", myJson);
if (myJson.statusCode != 200) {
  console.log("failed");
  return;
}
console.log("success");
return; 
}

API的CORS配置(根据图片内容整理)

AWS API Gateway的CORS配置详情:

  • 允许的来源:*
  • 允许的方法:POST, OPTIONS
  • 允许的请求头:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
  • 暴露的响应头:无
  • 缓存时间:0秒

问题分析与解决步骤

1. 移除前端请求中多余的CORS头部

Access-Control-Allow-Origin是服务器返回给前端的响应头,前端请求里带这个完全没用,反而可能干扰预检请求的正常处理。直接删掉这个头部即可,修改后的代码如下:

let body = { token: params.token};
const response = await fetch(
  url,
  {
    method: "POST",
    body: JSON.stringify(body),
    headers: { "Content-type": "application/json" },
  }
);
console.log(response);
try {
  const myJson = await response.json();
  console.log("response-->", myJson);
  if (myJson.statusCode !== 200) {
    console.log("failed");
    return;
  }
  console.log("success");
} catch (error) {
  console.error("响应解析失败:", error);
}
return;

2. 确保AWS API Gateway的CORS配置生效

  • 重新部署API:API Gateway修改CORS配置后,必须重新部署到对应阶段才会生效,别漏了这一步。
  • 检查OPTIONS方法:开启CORS时,API Gateway应该自动为资源创建OPTIONS方法,如果是手动配置的,要确保该方法返回200状态码,并且包含正确的CORS响应头(比如Access-Control-Allow-Origin: *)。
  • 测试预检请求:用curl发送OPTIONS请求验证,替换成你的API URL:
curl -X OPTIONS -H "Origin: null" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: Content-Type" https://your-api-id.execute-api.region.amazonaws.com/stage/resource

如果返回状态码是200,且响应头包含Access-Control-Allow-Origin: *,说明预检配置正常。

3. 避免origin为null的场景

你是直接本地打开HTML文件(origin为null),部分浏览器对这种情况的CORS限制更严格。可以用本地服务器运行HTML,比如:

  • Python 3:执行python -m http.server,然后访问http://localhost:8000/your-file.html
  • Node.js:用http-server包,安装后执行http-server访问对应地址

内容的提问来源于stack exchange,提问作者Aman Gautam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:25:19