【发布时间】:2020-01-29 17:31:33
【问题描述】:
这是我第一次使用 AWS,我确实设置了 DynamoDB 表并创建了 Lambda 函数来进行 CRUD 操作,我首先将函数设为静态。然后,我继续创建 API Gateway 方法来动态访问 Lambda 函数。
我尝试调用的方法是 GET 方法,它应该可以使用 JS 调用,并且可以从不同的域调用,我需要启用 CORS,不幸的是,即使在我的 lambda 函数的标头中有它之后,它也会给我 CORS错误:
'use strict';
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-2' });
exports.handler = async (event, context) => {
const ddb = new AWS.DynamoDB({ apiVersion: '2012-10-08' });
const documentClient = new AWS.DynamoDB.DocumentClient({ region: 'us-east-2' });
let responseBody = "";
let statusCode = 0;
var params = {
TableName: "Users",
};
// scan is a function, that is like the SELECT .. WHERE .. clause in SQL
try{
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data.Items);
statusCode = 200;
}catch(err) {
responseBody = `Unable to Scan Users, error: ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"access-control-allow-origin": "*"
},
body: {
responseBody
}
};
return response;
};
这是我在 VueJS 应用程序中的代码,它应该向 API Gateway 中的 GET 方法发出请求:
try{
const res = await axios.get("https://here-goes-my-url");
console.log(res.data);
} catch (err){
console.log(err);
}
这是我得到的错误:
Access to XMLHttpRequest at 'https://here-goes-the-url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Lambda GET 方法应返回“用户”表中的所有项目。 请帮忙,谢谢!
【问题讨论】:
-
API 网关上是否启用了 CORS,您是否使用 Lambda 代理集成?
-
是的,我确实在 API Gateway 中启用了 CORS,并且我正在使用 Lambda 代理集成,但仍然是同样的错误!
-
请您尝试将“Access-Control-Allow-Origin”大写。你是如何部署的?无服务器框架,SAM,还是手动?
标签: node.js amazon-web-services aws-lambda axios