0

我创建了一个使用x-google-backend云功能的 API 网关。

当我尝试通过浏览器访问它时,我收到了一个 CORS 错误,因此我研究并通过将其添加到 OpenAPI 配置中找到了解决方案,其中address部分与云功能相同。

options:
  operationId: cors
  x-google-backend:
    address: https://europe-west3-myproject.cloudfunctions.net/api/query
  responses:
    '200':
      description: A successful response

这行得通!于是我把云功能的公共访问权限去掉了,给网关服务帐号访问权限,再试一次。

这给了我一个权限错误。经过研究,我发现这篇文章解释了这个问题并给了我解决它的方法。问题是我用一个额外的调用路径来调用我的定义云函数query。我将此添加到 OpenAPI 配置中:

jwt_audience: https://europe-west3-myproject.cloudfunctions.net/api

所以我在 Postman 中再次尝试它并且它可以工作,但是在浏览器中我现在再次遇到 CORS 错误。

所以现在我在第一方……我该怎么办?这是我完整的 OpenAPI 配置:

# openapi2-functions.yaml
swagger: '2.0'
info:
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /query:
    post:
      operationId: api
      parameters:
        - in: "body"
          name: "message"
          schema:
            $ref: '#/definitions/messasge'
      x-google-backend:
         address: https://europe-west3-myproject.cloudfunctions.net/api/query
         jwt_audience: https://europe-west3-myproject.cloudfunctions.net/api
           x-google-quota:
            metricCosts:
          "read-requests": 1
      security:
        - api_key: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
    options:
      operationId: cors
      x-google-backend:
        address: https://europe-west3-myproject.cloudfunctions.net/api/query
      responses:
        '200':
          description: A successful response
securityDefinitions:
 # This section configures basic authentication with an API key.
  api_key:
    type: "apiKey"
    name: "key"
    in: "query"
x-google-management:
  metrics:
    # Define a metric for read requests.
    - name: "read-requests"
      displayName: "Read requests"
      valueType: INT64
      metricKind: DELTA
  quota:
    limits:
     # Define the limit or the read-requests metric.
      - name: "read-limit"
        metric: "read-requests"
        unit: "1/min/{project}"
        values:
          STANDARD: 100

definitions:
  chatmessage:
    type: "object"
    properties:
      id:
        type: string
        description: session id
        example: "2vr34524tg3"
      query:
        type: string
        description: message 
        example: "Hello"
    required:
      - id
      - query
4

1 回答 1

1

根据 Cloud Functions 上的文档跨域资源共享 (CORS) 有一些限制:

CORS 预检请求在没有Authorization标头的情况下发送,因此它们将在所有非公共 HTTP 函数上被拒绝。因为预检请求失败,所以主请求也会失败。

为了在您的情况下克服此限制,上述文档建议部署Cloud Endpoints 代理启用 CORS。此外,您可能会发现支持 CORS 文档页面对可用的 CORS 支持选项的描述很有用

于 2021-12-20T09:55:47.493 回答