【发布时间】: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