繁体   English   中英

带有 Typescript 的 CORS 错误无服务器框架?

[英]CORS error Serverless Framework with Typescript?

我被困在这个基本的 CORS 问题上,但似乎没有任何帮助。

尝试了无服务器 CORS 生存指南中的所有内容( https://www.serverless.com/blog/cors-api-gateway-survival-guide/

在无服务器离线中一切正常

第 1 部分无服务器离线

在这里,我得到了相同的所有预期响应标头

第 2 部分无服务器离线

浏览器中的错误-

CORS 策略已阻止从源“https://XXXXXXXXX.com”访问“https://XXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/spaces_config/ap1”获取:请求Access-Control-Allow-Headers 在预检响应中不允许标头字段 access-control-allow-origin。

我的设置->

我正在使用这个样板-> https://github.com/serverless/examples/aws-node-rest-api-typescript

无服务器.yml-

provider:
  name: aws
  runtime: nodejs16.x
  memorySize: 512
  timeout: 30
  environment:
    NODE_ENV: dev

plugins:
  - serverless-plugin-typescript
  - serverless-offline

package:
  exclude:
    - config/.env.stg
    - config/.env.pro
  include:
    - config/.env.dev

functions:
  createSpace:
    handler: handler.createSpace
    events:
      - http:
          path: spaces
          method: post
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: true
  findSpace:
    handler: handler.findSpace
    events:
      - http:
          path: spaces
          method: get
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: true

  findSpaceConfig:
    handler: handler.findSpaceConfig
    events:
      - http:
          path: spaces_config
          method: get
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: true
  updateSpaceConfig:
    handler: handler.updateSpaceConfig
    events:
      - http:
          path: spaces_config/{space_id}
          method: put
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: true
  findOneSpaceConfigById:
    handler: handler.findOneSpaceConfigById
    events:
      - http:
          path: spaces_config/{space_id}
          method: get
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: true

也尝试过 cors: true

Handler.js 文件-

import { Handler, Context, APIGatewayEvent } from "aws-lambda";
import dotenv from "dotenv";
// import middy from "middy";
// import { cors } from "middy/middlewares";

// cross-env NODE_ENV=dev ts-node handler.ts
dotenv.config({
  path: `config/.env.${process.env["NODE_ENV"]}`,
});

export * from "./app/connections/mongo";

import { SpacesController } from "./app/controller/spaces";
import { spaces } from "./app/model/spaces";

import { SpacesConfigController } from "./app/controller/spaces_config";
import { spaces_config } from "./app/model/spaces_config";
// Spaces

const spacesController = new SpacesController(spaces);

export const createSpace: Handler = (
  event: APIGatewayEvent,
  context: Context
) => {
  return spacesController.create(event, context);
};

export const findSpace: Handler = () => spacesController.find();

// Spaces Config

const spacesConfigController = new SpacesConfigController(spaces_config);

export const findSpaceConfig: Handler = () => spacesConfigController.find();

export const updateSpaceConfig: Handler = (event: APIGatewayEvent) =>
  spacesConfigController.update(event);

export const findOneSpaceConfigById: Handler = (
  event: APIGatewayEvent,
  context: Context
) => {
  return spacesConfigController.findOne(event, context);
};

// export const findOneSpaceConfigById = middy(findOneSpaceConfigByI).use(cors());

在样板文件中,有一个文件 message.ts( https://github.com/serverless/examples/blob/master/aws-node-rest-api-typescript/app/utils/message.ts ),我们可以在其中自定义响应。 在 middy 无法正常工作后,我尝试手动发送响应标头。

当我使用 middy 时,我没有收到任何响应头。

消息.ts-

import { ResponseVO } from "../types/response";

enum StatusCode {
  success = 200,
}

class Result {
  private statusCode: number;
  private code: number;
  private message: string;
  private data?: any;

  constructor(statusCode: number, code: number, message: string, data?: any) {
    this.statusCode = statusCode;
    this.code = code;
    this.message = message;
    this.data = data;
  }

  /**
   * Serverless: According to the API Gateway specs, the body content must be stringified
   */
  bodyToString() {
    return {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": true,
        "Content-Type": "application/json",
        "Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,OPTIONS",
        "Access-Control-Allow-Headers":
          "Content-Type, Accept, x-access-token ,Authorization",
      },
      statusCode: this.statusCode,
      body: JSON.stringify({
        code: this.code,
        message: this.message,
        data: this.data,
      }),
    };
  }
}

export class MessageUtil {
  static success(data: object): ResponseVO {
    const result = new Result(StatusCode.success, 0, "success", data);

    return result.bodyToString();
  }

  static error(code: number = 400, message: string) {
    const result = new Result(StatusCode.success, code, message);

    console.log(result.bodyToString());
    return result.bodyToString();
  }
}

使用的依赖项-

依赖项

卡在这个问题上很长时间了。

任何帮助将不胜感激。

谢谢

发生此问题的原因可能是浏览器的 JavaScript 发送的标头不在 serverless.yml 的允许列表中。 您可能不需要发送这些标头,因为从浏览器发送它们无助于解决 CORS 并且可能会使它复杂化。 我建议从您的 message.ts 中删除除 Content-type 之外的所有标题,然后重试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM