【问题标题】:AWS API call is being blocked by the CORS policyAWS API 调用被 CORS 策略阻止
【发布时间】:2021-06-22 06:40:41
【问题描述】:

我创建了一个 DynamoDB 表并为其附加了 3 个 lambda 函数。我试图通过将 API Gateway 触发器附加到它们来调用这些函数。我创建了一个 Rest API,然后创建了 get 方法。之后,我部署了 API,API 链接按预期工作。我现在尝试在 React 中使用 Axios 调用 API。

axios.get("Link")
  .then(res => {
    console.log(res);
  })

问题是每当我尝试在本地服务器上运行它时,都会收到以下错误。

Access to XMLHttpRequest from origin 'http://localhost:3000' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试在 API Gateway 上启用 CORS,但这也不起作用。我知道问题出在后端的某个地方,但我不知道我应该做什么。

【问题讨论】:

  • 您是否为 lambda / api 网关配置了任何 CORS? localhost:3000 是允许的域之一吗?
  • 我确实为 API 网关配置了 CORS,但我从未对 localhost 做过任何事情。

标签: reactjs amazon-web-services rest axios cors


【解决方案1】:

如果您启用了 CORS,那么这是预期的行为。除非另有配置,否则 CORS 将不允许其他域访问您的 API。

从这里检查如何在 API-Gateway 上正确配置 CORS:https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

对于您的开发/测试/学习环境,您可以禁用* CORS,然后您可以从 localhost 调用 API。

有关 API Gateway CORS 问题的更多疑难解答: https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cors-errors/

*基于安全原因不推荐使用

【讨论】:

    【解决方案2】:

    尝试在禁用 CORS 安全性的情况下打开 chrome。

    Mac 操作系统:

    open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 2020-09-11
      • 2021-04-16
      • 2018-02-26
      • 2019-11-19
      相关资源
      最近更新 更多