首页 > 解决方案 > React.js - CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。[AWS - Lambda - API 网关]

问题描述

我有一个将表单数据发送到的反应客户端应用程序AWS API Gateway。当我测试 API 时Postman一切正常,但是当我Axios在 react 中使用时,控制台中显示错误:

Access to XMLHttpRequest at 'https://execute-api.eu-west-3.amazonaws.com' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在 API Gateway 方法中启用了 CORS,也是我AWS Lambda functionLambda proxy integration,但显然它并没有解决问题。

我怎样才能解决这个问题 ?提前致谢。

- - - 更新 - - - -

根据评论,这是我从以下位置发送的响应的构建函数Lambda function

const buildResponse = (statusCode, body) => {
return {
    statusCode : statusCode,
    headers : {
        "Content-Type" : "application/json",
        "Access-Control-Allow-Headers" : "Content-Type",
        "Access-Control-Allow-Origin": "*",
    },
    body : JSON.stringify(body)
}
}

我打电话的地方:

const get = async () => {
const params = {
  TableName: dynamoTable
}
const all= await scanDynamoRecords(params, []);
const body = {
  data: all
}
return buildResponse(200, body);
}

标签: reactjsamazon-web-servicesaws-lambdacorsaws-api-gateway

解决方案


尝试像这样为 axios 启用凭据:

axios.defaults.withCredentials = true;

推荐阅读