【发布时间】:2021-06-01 15:32:35
【问题描述】:
我有一个用 React JS 编写的应用程序,在 localhost 上运行,它对 AWS 中的 API Gateway 进行 API 调用。 API Gateway 将请求转发到 lambda 函数,该函数返回响应。我在 AWS 端启用了 CORS。 此刻,每当我单击应用程序中的“请求”按钮时,我都会收到来自网关的响应。这是我当前的python代码:
import json
def lambda_handler(event, context):
response = {}
response['result'] = "Success"
response['message'] = "Updated successfully!"
return {
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
},
"body": json.dumps(response)
}
这是请求的正文:
{
"ID": "1101",
"RequestDate": "2021-02-28"
}
这很好用。我从此响应中获得了“消息”值,并且可以毫无问题地显示它。
接下来我想显示包含来自请求的一些数据的信息。例如,我想从请求中获取RequestDate,而不是Updated successfully,并返回Updated successfully on 2021-02-28。
我添加了这两行:
def lambda_handler(event, context):
body = json.loads(event['body'])
request_date = body['RequestDate']
response = {}
response['result'] = "Success"
response['message'] = "Updated successfully!"
return {
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
},
"body": json.dumps(response)
}
在我进行此更改后,我会在我的应用程序中获得以下代码:
Access to fetch at url 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.
只有当我添加 request_date = body['RequestDate'] 时才会发生这种情况。我试着只归还尸体,它也能正常工作。
在我的 react js 应用程序中,我还添加了以下标头:
async callAPI(url, method, data) {
let result = await fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
data
})
})
return result.json().then(body => this.notify(body['message']));
}
我尝试启用 CORS 并再次部署资源,但无济于事。我已将 Access-Control-Allow-Origin 添加到 AWS 中允许的标头中。正如我所提到的,在添加一行之前,它与 post 方法一起工作得很好。这里可能出了什么问题,我该如何补救?
编辑: 还有一件事。我仅从在 localhost 上运行的应用程序中收到此错误。卷曲或使用任何 REST 客户端都可以正常工作。
编辑2: 添加获取代码
【问题讨论】:
-
你可以尝试从 lambda 返回
'Access-Control-Allow-Headers':'*'吗? -
试过了,还是一样
标签: amazon-web-services cors aws-api-gateway