【以下的问题经过翻译处理】 我有一个工作流程
Postman -> APIGateway -> Lambda -> Amazon Translate
当我从Postman发送请求时,它一切正常。但当我从静态网站发送请求(尝试了本地和部署到S3上的网站),我遇到了CORS错误。
Access to fetch at 'myapigatawaylink' from origin 'myStaticWebsiteDeployedFromS3' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
我阅读了Amazon的文章,要么我没有理解某些内容,要么漏掉了某些内容,我已经尝试在各个地方修复这个CORS策略:
- 前端
const response = await fetch("mygatawayapilink/dev/trialrsrc", {
// mode: 'no-cors', commented out, It doesn´t give error if i discomment it but i get no response (200 empty)
method: "POST",
body: JSON.stringify({
text: e.target[0].value
}),
headers: {
"Content-type": "application/json",
'Access-Control-Allow-Origin': "*",
}
})
.then(res => res.json())
- Lambda函数
exports.handler = async (event) => {
const AWS = require("aws-sdk");
AWS.config.update({region: "eu-west-1"});
const translate = new AWS.Translate();
let params = {
SourceLanguageCode: 'auto',
TargetLanguageCode: 'es',
Text: event.text
};
const translated = await translate.translateText(params).promise();
return {
statusCode:200,
headers: {
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: translated
}
};
- API Gateway:我有GET、POST和OPTIONS方法,我已经对所有这些方法执行了操作 -> 启用CORS。
是否可能修复它,还是我必须使用其他服务,如CloudFront或代理?