我正在尝试从 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”标头。因此,不允许访问源“ http://localhost:5000 ”。响应具有 HTTP 状态代码 403。
我试图在 POST 方法的 API 网关中启用 CORS,但这并没有改变结果。
我也尝试在 yaml 文件中明确设置 CORS
functions:
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors:
origin: '*'
仍然没有运气。
有谁知道我在这里做错了什么?
一件奇怪的事情是,我可以通过 PostMan 让帖子正常工作,但如果我通过我的应用程序尝试它,它就会中断。
谢谢
更新
当我这样做serverless deploy
时,它会像上图一样显示在 AWS 中,方法如下所示
正如我之前所说,我尝试直接从 API Gateway 控制台启用 CORS,但尝试调用该方法时没有区别。