reactjs - 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 function
的Lambda 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);
}
解决方案
尝试像这样为 axios 启用凭据:
axios.defaults.withCredentials = true;
推荐阅读
- javascript - 什么是中间值?
- c# - Windows 应用程序中的自动完成功能
- ckeditor - CK 编辑器未粘贴源格式,例如:段落(换行)换行符
- css - 如果CSS中的另一个元素存在href,则将样式应用于类的元素
- r - 瑞典语字符的文本编码在 YAML 中出错
- laravel - Laravel 5 如何从控制器传递单个变量并在刀片视图文件中捕获相同的变量?
- android - 将活动实例传递给类可以吗?
- ios - _UIRemoteView - 在 Xcode 中显示视图层次结构
- typescript - Moodle 移动定制应用程序编译
- wordpress - Wordpress 搜索 - 如何从标题或元键搜索?获得两个结果