网站搜索

为 Azure Function API(TypeScript)创建 swagger 文档


我需要你的帮助,请。

我使用 Azure 函数 创建了一个 Rest API,它可以返回托管在云端的 CosmoDB 数据库中的用户列表。

我想为这个 API 创建 swagger 文档,知道我在 API 中使用的是 Azure Function v2,语言是 TypeScript。

这是我的代码类型脚本(index.ts)

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import { CosmosClient } from "@azure/cosmos";  // @azure/cosmos c'est notre kit Azure Cosmos DB SQL JavaScript SDK 
const httpTrigger: AzureFunction = async function(
  context: Context,
  req: HttpRequest
): Promise<void> {
  try {


    const client = new CosmosClient(process.env.CONNECTION_STRING); 
    const database = client.database(process.env.COSMOS_DB_NAME);
    const container = database.container(process.env.COSMOS_DB_COLLECTION1_NAME);

    
    let iterator = container.items.readAll();
    let { resources } = await iterator.fetchAll();
    
    context.res = {
      body: resources
    };

  } catch (err) {
    context.res = {
      status: 500,
      body: err.message
    };
  }
};

export default httpTrigger;

项目

这是我的文件 swagger.yml

swagger: '2.0'
info:
  title: APIAzureFunction
  version: '2.0'
host: localhost:7071
basePath: /api
schemes:
  - https
  - http
paths:
  '/utilisateurs':
    get:
      tags:
        - Utilisateurs
      summary: Retourner toutes les utilisateurs.
      consumes:
        - application/json
      responses:
        '200':
          description: la liste des utilisateurs
          schema:
            type: object
            required:
              - userName
            properties:
              id:
                type: string
              nom:
                type: string
              prénom:
                type: string
              mdp:
                type: number
              Active:
                type: boolean    
  

在 Swagger 中预览 Swagger 预览

我想在 Swagger 中显示用户列表,为此我编写了文档 yml(swagger.yml)。当我在 Swagger 编辑器中执行获取用户的请求时,我收到此错误:TypeError: Failed to fetch。

这是一个错误的图片:

谢谢你的帮助

答案#1

根据您提供的信息,我可以重现该问题。这是一个跨域(CORS)问题。VS Code 的 Swagger 预览或 Swagger 编辑器是单页应用程序。当我们在它们中从不同的域访问 API 时,我们会遇到 CORS 问题。因此我们需要为我们的 Azure Function 配置 CORS。关于如何配置它,请参考这里和这里。

例如

我的文件 swagger.yml

swagger: '2.0'
info:
  title: APIAzureFunction
  version: '2.0'
host: localhost:7071
basePath: /api
schemes:
  - http
paths:
  '/http':
    get:
      tags:
        - Http
      summary: query cosmos db.
      consumes:
        - application/json
      responses:
        '200':
          description: response
             

我的函数代码

import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { CosmosClient } from "@azure/cosmos";
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    context.log('HTTP trigger function processed a request.');
    try {


        const client = new CosmosClient(''); 
        const database = client.database('');
        const container = database.container('');
    
        
        let iterator = container.items.readAll();
        let { resources } = await iterator.fetchAll();
        
        context.res = {
          body: resources,
          headers: {
            'Content-Type': 'application/json'
        }
        };
    
      } catch (err) {
        context.res = {
          status: 500,
          body: err.message
        };
      }
};

export default httpTrigger;

  • 我没有为我的函数配置 CORS

  • 我为函数配置了 CORS(我在本地测试)

请在 local.settings.json 中添加以下设置以实现它

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node"
    
  },
  "Host": {
    "CORS": "*"
  }
}