【发布时间】:2018-03-19 13:07:01
【问题描述】:
我正在尝试从 angularjs 应用程序向我使用无服务器设置的 lambda 函数发出 http 请求。
这是我的 serverless.yaml 函数
functions:
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors: true
创建客户函数
module.exports.createcustomer = (event, context, callback) => {
let customer = JSON.parse(event.body).customer;
service.create(customer, function(result) {
let response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
body: JSON.stringify({
result: 'Created Customer Successfully',
message: 'The account has been created!',
type: 'success',
customer: result
})
};
callback(null, response);
});
};
在我的 AngularJS 应用中,我这样称呼它
app.factory('MyFactory', ['$http', function($http) {
return {
CreateCustomer: function(customer) {$http.post('<apipath>/createcustomer', {customer:customer})}
}
}]);
但是,我不断收到此错误:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:5000' 不允许访问。响应的 HTTP 状态代码为 403。
我尝试在 API 网关中的 POST 方法中启用 CORS,但这并没有改变结果。
我也尝试在 yaml 文件中明确设置 CORS
functions:
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors:
origin: '*'
还是没有运气。
有谁知道我在这里做错了什么?
一个奇怪的事情是,我可以通过 PostMan 让帖子正常工作,但如果我通过我的应用程序尝试它会中断。
谢谢
更新
当我执行serverless deploy 时,它会像上图一样显示在 AWS 中,方法如下所示
如前所述,我尝试直接从 API Gateway 控制台启用 CORS,但尝试调用该方法时没有任何区别。
【问题讨论】:
-
尝试将 Access-Control-Allow-Headers 标头添加到 lambda 响应中。
-
@KaustubhKhare 试过了,还是不行。
-
根据您发布的内容看起来不错。我会检查 API Gateway 控制台和 Lambda 控制台,以检查这些设置是否真正得到正确反映和部署。
-
如果我在 Angular 的 http 请求中将 Content-Type 设置为 text/plain,我可以获得响应,但使用 application/json 会失败。
-
与发送预检选项检查有关,但是当我在 api 路径上设置选项时,发送 application/json 时仍然失败
标签: amazon-web-services lambda aws-api-gateway serverless