我正在尝试根据 API Gateway 使用 Lambda 的发布请求将项目添加到 DynamoDB。
这是我的 Lambda 代码的样子:
var AWS = require('aws-sdk');
var dynamoDB = new AWS.DynamoDB();
exports.handler = (event, context, callback) => {
var temp_id = "1";
var temp_ts = Date.now().toString();
var temp_calc = event['params']['calc'];
var params = {
TableName:"calc-store",
Item: {
Id: {
S: temp_id
},
timestamp: {
S: temp_ts
},
calc: {
S: temp_calc
}
}
};
dynamoDB.putItem(params,callback);
const response = {
statusCode: 200,
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: event['params']['calc']
};
callback(null, response);
};
这就是我从客户端调用函数的方式
axios.post(apiURL, {params:{calc:calc}})
.then ((res) => {
console.log(res);
})
我在我的 API 网关上启用了 30 多次 CORS,并且我还通过向响应添加标头进行了双重检查。但是无论我做什么,我都会不断收到 CORS 错误,并且由于某种原因,在我的回复中,我可以看到没有附加“Access-Control-Allow-Origin”标头。
POST https://egezysuta5.execute-api.us-east-1.amazonaws.com/TEST 502
localhost/:1 Failed to load https://egezysuta5.execute-api.us-east-
1.amazonaws.com/TEST: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:3000' is
therefore not
allowed access. The response had HTTP status code 502.
createError.js:17 Uncaught (in promise) Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:87)
我尝试不使用 Lambda 代理集成,然后它工作了,但是,我无法访问我传递的参数。
编辑:在花了几个小时之后,这就是我将问题归结为的原因。我的客户正在向 OPTIONS 发出成功的飞行前请求。OPTIONS 成功返回了正确的 CORS 标头,但由于某种原因,这些标头没有传递给我的 POST 请求!
EDIT2:(这不能解决问题)如果我将响应正文更改为字符串,则没有错误!有问题
event['params]['calc']