[英]Error when sending an external request from AWS through Node.js and Axios
[英]CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function
我在 React 前端使用 axios 将数据发布到 DynamoDB 表。 API 是通过无服务器配置在 AWS 上使用 API 网关和 Lambda 设置的。
当请求通过并且我在数据库中看到添加的项目时,我仍然收到 CORS 错误https://i.stack.imgur.com/m7yMG.jpg
这是 axios 方法:
import axios from "axios";
export const sendItemToDB = async (_data) => {
if (!_data) { return };
try {
const res = await axios({
method: "POST",
url: process.env.REACT_APP_QUERY_API,
data: _data,
headers: {
"Content-Type": "text/plain"
},
});
console.log("data returned from api", res);
} catch (error) {
console.log("Error sending File to db: ");
console.log(error);
}
};
Lambda 上的 API 方法:
const createRecord = async (event) => {
const response = { statusCode: 200 };
try {
const body = JSON.parse(event.body);
const params = {
TableName: process.env.DYNAMODB_TABLE_NAME,
Item: marshall(body || {}),
};
const createResult = await db.send(new PutItemCommand(params));
response.body = JSON.stringify({
message: "Successfully created record.",
createResult,
});
} catch (e) {
console.error(e);
response.statusCode = 500;
response.body = JSON.stringify({
message: "Failed to create record.",
errorMsg: e.message,
errorStack: e.stack,
});
}
return response;
};
我将此配置基于本教程: https ://github.com/jacksonyuan-yt/dynamodb-crud-api-gateway
我按照亚马逊文档解决了这个问题并重新配置了无服务器部署 yml。
关于 api 网关和 lambda 代理集成的无服务器文档在这里
将缺失的标头添加到所有 lambda 函数中是必不可少的。
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
};
还测试 OPTIONS 是否适用于预检: https ://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-test-cors.html
正如 Stavros 注意到的那样,问题在于这不是一个简单的跨源 POST 方法请求(因为它包含自定义标头),因此您需要通过添加来调整AWS API Gateway的CORS 设置
你可以通过这样的控制台来完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.