【问题标题】:AWS Lambda + Gateway API + React JSAWS Lambda + 网关 API + React JS
【发布时间】:2020-10-07 22:03:34
【问题描述】:

我正在尝试使用 react 发布到我的 dynamoDB,但是我收到以下错误:

Access to fetch at 'https://xxxxx.execute-api.us-west-2.amazonaws.com/prod/getuserprofile' from 
origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource. If an opaque response serves your needs, set the 
request's mode to 'no-cors' to fetch the resource with CORS disabled.

首先,我使用 Lambda 测试检查了此方法是否有效。

我也用过curl -v -X OPTIONS https://xxxx.execute-api.us-west-2.amazonaws.com/prod/getuserprofile,它的输出是:

`< HTTP/2 200
< date: 
< content-type: application/json
< content-length: 0
< x-amzn-requestid:
< access-control-allow-origin: *
< access-control-allow-headers: Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token
< x-amz-apigw-id:
< access-control-allow-methods: DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT`

但是,当我尝试 react.js fetch 函数时,它会抛出错误。

fetch("https://xxxx.execute-api.us-west-2.amazonaws.com/prod/getuserprofile", {
  method: 'PUT',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },      
  body: JSON.stringify({key1: email, name, message})
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
});

我尝试在 fetch 函数中添加“模式”,但无济于事。 任何调试建议也会有帮助。谢谢。

【问题讨论】:

    标签: reactjs amazon-web-services cors fetch


    【解决方案1】:

    如果有人想知道我的问题的答案: 这是因为您必须重新部署才能使 CORS 生效。

    所以:

    1. 转到您的 API。

    2. 在左侧菜单栏上转到资源。

    3. 点击您的资源

    4. 点击操作栏 > 启用 CORS

    5. 阶段 > 部署

    【讨论】:

      【解决方案2】:

      跨域资源共享 (CORS) 是一种机制,它使用额外的 HTTP 标头告诉浏览器让在一个来源运行的 Web 应用程序可以访问来自不同来源的选定资源。当 Web 应用程序请求的资源与其自己的来源(域、协议或端口)不同时,它会执行跨域 HTTP 请求。

      以下是 CORS 的 AWS 文档。

      https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

      【讨论】:

      • 在我的 lambda node.js 函数中,我确实有这个 CORS 策略:callback(null, { statusCode: 201, body: JSON.stringify({ email: params.Item.email, message: params. Item.message,用户名:params.Item.name,}),标题:{ 'Access-Control-Allow-Origin': '*', }
      猜你喜欢
      • 2019-05-02
      • 2019-05-10
      • 2021-03-02
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多