第 20
篇 辗转来到nodejs了,nodejs+express+swagger
背景:使用nodejs搭建了一个后端服务,暴露出的接口需要提供接口文档。选择并使用swagger,并通过注释的方式编写swagger文档。
接入swagger没有技术难度,只需要熟读API即可完成。更详细的配置还需要阅读swagger API进行获取,下面列举具体的接入过程:
1. 安装swagger-jsdoc
npm i swagger-jsdoc
2. swagger-jsdoc配置文件
新建用于swagger配置的文件,配置的内容包括:
const path = require('path')
const express = require('express')
const swaggerUI = require('swagger-ui-express')
const swaggerDoc = require('swagger-jsdoc')
// swaggger-jsdoc配置
const options = {
definition: {
openapi: '3.1.0',
info: {
title: 'nodejs-server',
version: 'V1.0.0',
decription: 'This is a nodejs server',
contact: {
name: 'name',
url: 'url',
},
},
servers: [
{
url: 'xxx',
description: 'server url',
}
],
},
// 去哪个路由下收集swagger
apis: [path.join(__dirname, '../../router/*.js')]
}
let swaggerSpec = swaggerDoc(options)
let swaggerJSON = function(req, res) {
res.setHeader('Content-Type', 'application/json')
res.send(swaggerSpec)
}
let swaggerInstall = function(app) {
if(!app) {
app = express()
}
// 开放接口
app.get('/nodejs-server/swagger.json', swaggerJSON)
// 使用swaggerSpec生成swagger文档页面,并开放在指定路由
app.use('/nodejs-server/swagger', swaggerUI.serve, swaggerUI.setup(swaggerSpec))
}
module.exports = swaggerInstall
3. 执行swaggerInstall
在nodejs服务的入口文件index.js
中,引入swagger配置文件,并执行swaggerInstall。
const swaggerInstall = require('./utils/swagger/index')
swaggerInstall(app)
4. 添加注释
如,测试服务连接的接口,可配置如下内容:
/**
* @swagger
* /nodejs-server/: #路由地址
* get:
* tags:
* - controller #接口分类
* summary: 测试服务器连接 #接口备注
* description: 测试服务器连接 #接口描述
* consumes:
* - "application/json" #接口接收参数方式
* requestBody: #编写参数接收体
* required: true #是否必传
* content:
* application/json:
* schema: #参数备注
* type: object #参数类型
* properties:
* username:
* type: string #参数类型
* description: 用户名 #参数描述
* password:
* type: string #参数类型
* description: 密码 #参数描述
* example: #请求参数样例。
* username: "string"
* password: "string"
* responses: #编写返回体
* 200: #返回code码
* description: 获取成功 #返回code码描述
* content:
* application/json:
* schema:
* type: object
* properties:
* code: #返回的code码
* type: string
* description: 返回code码
* msg: #返回体信息。***注意写的位置一定要和res_code对齐。
* type: string #返回体信息类型
* description: 返回信息
* data:
* type: object
* description: 返回数据
* -1:
* description: 注册失败
* */
5. 启动服务,运行swagger
swagger启动端口使用nodejs监听的端口即可。效果如下图:
😒工不好打,总有一些人想让你前后端一起,贼人之心不死啊!没逃过,惨了/(ㄒoㄒ)/~~ 好惨的