来自S3上的静态网站的请求到API Gateway再到Lambda,由于CORS(跨源资源共享)问题被阻止,已尝试一切方法

0

【以下的问题经过翻译处理】 我有一个工作流程 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策略:

  1. 前端
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())
  1. 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
  }
};
  1. API Gateway:我有GET、POST和OPTIONS方法,我已经对所有这些方法执行了操作 -> 启用CORS。

是否可能修复它,还是我必须使用其他服务,如CloudFront或代理?

1 回答
0

【以下的回答经过翻译处理】 API Gateway在更改CORS策略后不会自动重新构建,我部署了每次更改,并最终使其正常运行

profile picture
专家
已回答 5 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则