首页 > 解决方案 > 无服务器 aws httpApi cors 设置

问题描述

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 文件和示例代码。

标签: amazon-web-servicesaws-lambdaaws-api-gateway

解决方案


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

functions:

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

推荐阅读