7

我正在尝试从 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,但尝试调用该方法时没有区别。

4

2 回答 2

7

您的屏幕截图更新显示未为任何这些资源设置 OPTIONS 方法。当您在控制台中为 API Gateway 资源启用 CORS 时,AWS 会自动进行设置。

当您为资源启用 CORS 时,您可以在 AWS 控制台中看到这种情况,但当然,您serverless deploy正在覆盖此配置。

/createcustomer通过无服务器部署在 AWS 中正​​确配置资源,您可以重写 serverless.yaml 的这一部分:

events: 
  - http: post /createcustomer
    cors: true

看起来像这样:

events:
  - http:
      path: /createcustomer
      method: post
      cors: true

我不是框架的 .yml 语法方面的专家,所以我无法准确解释为什么会这样。

尽管如此,我已经确认了这样的文件:

functions:
  deletecustomer:
    handler: handler.deletecustomer
    events:
      - http:
          path: /deletecustomer
          method: post
          cors: true
  createcustomer:
    handler: handler.createcustomer
    events: 
      - http: post /createcustomer
        cors: true

将在 AWS API Gateway 中创建两个资源,一个为 CORS 正确配置,一个缺少 OPTIONS 方法:

两种资源,一种正确,一种缺失 OPTIONS

于 2017-10-14T18:28:22.540 回答
1

这是可以提供帮助的配置。请注意,明确允许 CORS 来源始终是安全的。所以最好将源锁定到 localhost:{port-number}。此外,您还可以在 CORS 设置上启用凭据。请以以下无服务器配置为例:

cors:
  origin: 'http://localhost:4200'
  headers:
    - Content-Type
    - X-Amz-Date
    - Authorization
    - X-Api-Key
    - X-Amz-Security-Token
    - X-Amz-User-Agent
  allowCredentials: true

于 2017-10-10T06:14:30.153 回答