【问题标题】:Serverless aws httpApi cors setting无服务器 aws httpApi cors 设置
【发布时间】:2021-12-24 21:53:42
【问题描述】:
provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: '20201221'
  role: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  httpApi:
    cors:
      allowedOrigins:
        - '*'
      allowedMethods:
        - GET
        - OPTIONS
        - POST
        - PUT
        - DELETE
      allowedHeaders:
        - Content-Type
        - X-Amz-Date
        - Authorization
        - X-Api-Key
        - X-Amz-Security-Token
        - X-Amz-User-Agent
        - X-Transaction-Key
        - Access-Control-Allow-Origin
        - Access-Control-Allow-Methods
        - Access-Control-Allow-Headers
        - Access-Control-Allow-Credentials

functions:

  getOTP:
    handler: xxxx/xxxx.yyyy
    events:
      - httpApi:
          path: /xxxx/yyyy
          method: POST
      - httpApi:
          path: /xxxx/yyyy
          method: OPTIONS
module.exports.yyyy= async (event) => {
  const body = JSON.parse(event.body);


  return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*", // Required for CORS support to work
      "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
      "Access-Control-Allow-Headers" : "*",
      "Access-Control-Allow-Methods": "*",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      message: "yayay",
    }),
 };

抱歉英语不好。 我正在使用无服务器框架来构建 API 服务。 我只是按照无服务器文档在 aws 上构建 httpApi 事件。 但是 cors 设置不起作用。 这是我的 yml 文件和示例代码。

【问题讨论】:

  • 你遇到了什么错误?
  • 使用 POST api 调用时出现 cors 错误
  • 能否分享您通过 CLI 或任何其他方式进行的 API 调用?
  • 你能告诉我们所有的解决方法都做了什么尝试修复它,这样我们就可以节省时间。

标签: amazon-web-services aws-lambda aws-api-gateway


【解决方案1】:

httpAPI 上有很多关于 CORS 的解释。

  1. 在 Access-Control-Allow-Headers 中添加 x-api-key
  2. 明确定义您的路由方法

Refer here

【讨论】:

    【解决方案2】:

    您是否尝试在功能级别而不是服务级别设置 cors 配置?

    functions:
    
      getOTP:
        handler: xxxx/xxxx.yyyy
        events:
          - http:
              path: /xxxx/yyyy
              method: POST
              cors: true
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 2021-05-06
      • 2020-03-17
      • 2018-03-19
      • 1970-01-01
      • 2019-12-15
      • 2017-06-07
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多