0

在我的应用引擎实例前面实现了一个 api 网关后,我遇到了一个问题,指出请求由于 CORS 标头而被阻止。在线搜索后,我发现 API 网关没有提供设置 CORS 策略的方法,但是它也“覆盖”了我的单个后端应用程序发送的标头。我是否需要实现负载均衡器来设置额外的 Header 或者有办法避免覆盖?

API 示例:

paths:
  "/login":
    post:
      description: "Login into the service"
      operationId: "login"
      x-google-backend:
        address: https://project-id.oa.r.appspot.com/api/v1/login
      produces:
      - "application/json"
      responses:
        200:
          description: "Projects retrieved successfully"
          schema:
            $ref: "#/definitions/access_token"
        401:
          description: "Wrong password"
          schema:
            type: "string"
        404:
          description: "User not exists"
          schema:
            type: "string"
      parameters:
      - in: body
        name: user
        description: The user to create.
        schema:
          type: object
          required:
            - userName
          properties:
            userName:
              type: string
            firstName:
              type: string
            lastName:
              type: string
4

1 回答 1

1

经过大量试验,我找到了一个比在网关前实现负载均衡器更简单的解决方案:

要使用后端应用程序提供的 CORS 标头,只需OPTIONS向 API 添加请求以避免标头被覆盖。所以,给定登录 API,我只需要像这样添加请求:

paths:
  "/login":
    post:
      description: "Login into the service"
      operationId: "login"
      x-google-backend:
        address: https://project-id.oa.r.appspot.com/api/v1/login
      produces:
      - "application/json"
      responses:
        200:
          description: "Projects retrieved successfully"
          schema:
            $ref: "#/definitions/access_token"
        401:
          description: "Wrong password"
          schema:
            type: "string"
        404:
          description: "User not exists"
          schema:
            type: "string"
      parameters:
      - in: body
        name: user
        description: The user to create.
        schema:
          type: object
          required:
            - userName
          properties:
            userName:
              type: string
            firstName:
              type: string
            lastName:
              type: string
    options:
      description: "Cors associated request to login"
      operationId: "login cors"
      x-google-backend:
        address: https://project-id.oa.r.appspot.com/api/v1/login
      responses:
        200:
          description: "Allow"
        401:
          description: "Cors not allowed"
于 2021-03-21T02:03:19.680 回答