【问题标题】:Enabling CORS with openapi-generator使用 openapi-generator 启用 CORS
【发布时间】:2020-03-05 00:38:04
【问题描述】:

所以我使用openapi-generator 来生成一个烧瓶服务器来服务我的api。

我在生成运行它的服务器并在我的浏览器中查看端点时没有问题。但是,当我从我的 React Web 应用程序发出 GET 请求时,我收到了 CORS 错误。

我尝试了一些方法来启用 CORS。

我尝试将标头添加到我的 .yaml 中的端点。

/pipelines:
    get:
      summary: 'Returns a list of pipelines.'
      operationId: get_pipelines
      responses:
        '200':
          description: 'A JSON array of pipelines'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pipeline'
          headers:
            Access-Control-Allow-Origin: '*'
        default:
          description: Unexpected error
          content:
            'application/json':
              schema:
                $ref: '#/components/schemas/ErrorMessage'

当我尝试通过 .yaml 添加标头并尝试重新生成服务器模块时,我收到此错误:

-attribute paths.'/pipelines'(get).responses.200.Access-Control-Allow-Origin is not of type `object

我还尝试在服务器模块的 ma​​in.py 中安装和导入 flask_cors。

#!/usr/bin/env python3

import connexion

from openapi_server import encoder
from flask_cors import CORS

def main():
    app = connexion.App(__name__, specification_dir='./openapi/')
    CORS(app.app)
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('openapi.yaml',
                arguments={'title': 'ICDR API'},
                pythonic_params=True)
    app.run(port=5050)


if __name__ == '__main__':
    main()

我同时尝试了这两种方法。我在 swagger-codegen petstore.yaml 示例和 connexion docs 中找到了这些修复。

但是,正如我所说,我使用的是 openapi-generator,因此它与其他任何一种工具都有点不同,但是我很难找到有关如何正确设置它的任何信息。在谁能帮助我之前,有没有人使用过 openapi-generator?

【问题讨论】:

  • 您是否尝试提供实际链接而不是通配符? headers:Access-Control-Allow-Origin: 'http://localhost:3000/' 当我在 C# 中尝试时,这对我有用
  • 是的,这就是我首先做的,当我尝试生成服务器时遇到了同样的错误。 -attribute paths.'/pipelines'(get).responses.200.Access-Control-Allow-Origin is not of type 'object'
  • 将记录器添加到烧瓶 cors logging.getLogger('flask_cors').level = logging.DEBUG 然后您可以检查问题。将CORS(app.app) 移到app.run(port=5050) 之后
  • 我会试一试我目前已经转移到另一个更紧迫的问题,但一旦我回到这个问题,我会告诉你它是怎么回事。

标签: reactjs flask openapi-generator connexion


【解决方案1】:

OpenApi 代码生成器在后台使用 connexion 库,在他们建议使用 flask_cors 的文档中,请参阅:here

我目前正在使用从原件派生的自定义胡须模板,所以在 \__main__.mustache 我添加了这些行

from flask_cors import CORS
....
CORS(app.app)
app.run(port=.....)

确保安装 flask_cors 或将其添加到您的 requirements.txt 中

附:您可以使用generate ... -t TEMPALTE/FOLDER?LOCATION 指定模板位置

【讨论】:

  • 我和我的团队最终在我问这个问题的时候解决了这个问题,但这是正确的答案,所以我想我会给你功劳!
猜你喜欢
  • 2022-09-30
  • 2022-07-23
  • 2021-08-08
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2021-11-09
  • 2020-03-16
相关资源
最近更新 更多