在nodejs中使用swagger方式
在nodejs中使用swagger
在工作中和后臺javaer進(jìn)行接口調(diào)試的時候使用的是swagger,非常的方便。nodejs中有什么好用的api工具呢?網(wǎng)上查找了一下,swagger同樣適用于nodejs,記錄一下在nodejs中使用swagger的過程。
1、安裝依賴
npm install swagger-ui-express swagger-jsdoc -S
2、創(chuàng)建swagger中間件
- 在utils/swagger文件夾中創(chuàng)建index.js
- 配置swagger-jsdoc中的options
- 注意修改swagger收集注釋的路由
const path = require('path')
const express = require('express')
const swaggerUI = require('swagger-ui-express')
const swaggerDoc = require('swagger-jsdoc')
//配置swagger-jsdoc
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'api',
version: '1.0.0',
description: `小程序+管理后臺共用接口api`
}
},
// 去哪個路由下收集 swagger 注釋
apis: [path.join(__dirname,'../../routes/*.js')]
}
var swaggerJson = function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
}
const swaggerSpec = swaggerDoc(options)
var swaggerInstall = function(app) {
if (!app){
app = express()
}
// 開放相關(guān)接口,
app.get('/swagger.json', swaggerJson);
// 使用 swaggerSpec 生成 swagger 文檔頁面,并開放在指定路由
app.use('/swagger', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
}
module.exports = swaggerInstall
3、在app.js中引用swagger中間件的swaggerInstall方法
// 使用swagger API 文檔
var swaggerInstall = require('./utils/swagger')
swaggerInstall(app)4、swagger 在js 中的注釋如下所示
可在配置的路徑下任意js地方注釋,swagger-jsdoc會遍歷查找
/**, * @swagger * /api/addExam: * post: * tags: * - 測試 * summary: 提交考試答案 * produces: * - application/json * parameters: * - name: name * in: query * description: 姓名 * required: false * type: integer * maximum: * minimum: 1 * format: * - name: phone * in: query * description: 電話 * required: false * type: integer * maximum: * minimum: 1 * format: * responses: * 200: * description: successful operation * schema: * ref: #/definitions/Order * 400: * description: Invalid ID supplied * 404: * description: Order not found * */
5、訪問api
- npm start 運行項目
- 輸入 http://localhost:3000/swagger 訪問本地api

nodejs egg框架 自動生成swagger文檔
npm install egg-swagger-doc --save
/* /config/config.default.js */
/ egg-swagger-doc 配置信息。
exports.swaggerdoc = {
dirScanner: './app/controller', // 配置自動掃描的控制器路徑。
// 接口文檔的標(biāo)題,描述或其它。
apiInfo: {
title: 'NAPI', // 接口文檔的標(biāo)題。
description: 'swagger-ui for NAPI document.', // 接口文檔描述。
version: '1.0.0', // 接口文檔版本。
},
schemes: ['http', 'https'], // 配置支持的協(xié)議。
consumes: ['application/json'], // 指定處理請求的提交內(nèi)容類型(Content-Type),例如application/json, text/html。
produces: ['application/json'], // 指定返回的內(nèi)容類型,僅當(dāng)request請求頭中的(Accept)類型中包含該指定類型才返回。
securityDefinitions: { // 配置接口安全授權(quán)方式。
// apikey: {
// type: 'apiKey',
// name: 'clientkey',
// in: 'header',
// },
// oauth2: {
// type: 'oauth2',
// tokenUrl: 'http://petstore.swagger.io/oauth/dialog',
// flow: 'password',
// scopes: {
// 'write:access_token': 'write access_token',
// 'read:access_token': 'read access_token',
// },
// },
},
enableSecurity: false, // 是否啟用授權(quán),默認(rèn) false(不啟用)。
// enableValidate: true, // 是否啟用參數(shù)校驗,默認(rèn) true(啟用)。
routerMap: true, // 是否啟用自動生成路由,默認(rèn) true (啟用)。
enable: true, // 默認(rèn) true (啟用)。
};* /config/plugin.js */
'use strict';
// 配置 egg-swagger-doc 插件信息。
exports.swaggerdoc = {
enable: true, // 是否啟用。
package: 'egg-swagger-doc', // 指定包名稱。
};/* /app/contract/format.js */
//自動文檔約定
module.exports = {
JsonBody: { // 這個名字對應(yīng)上面 Controller 注釋的@response 的 JsonBody。
result: { type: 'string' }, // 服務(wù)器返回的數(shù)據(jù)。
},
};編寫一個controller控制器
'use strict';
const BaseController = require("../base");
/**
* @controller 測試控制器 注釋必寫,swagger-doc是根據(jù)這段注釋來生成接口的 )。
*/
class HomeController extends BaseController {
/** ( 注釋必寫,swagger-doc是根據(jù)這段注釋來生成接口詳細(xì)信息的 )。
* @summary 根據(jù)ID查詢信息。
* @description 根據(jù)ID查詢信息。
* @router get /api ( get 表示設(shè)置請求為 get 請求,最后的 selectById 對應(yīng)下面的 selectById 方法 )。
* @request query integer Id 需要去查新的ID。( get 對應(yīng) query 請求,請求值設(shè)定為 integer 純數(shù)字類型,ID 為請求的字段,注意大小寫,和下面的方法要一一對應(yīng),不然會報錯 )。
* @response 200 JsonBody 返回結(jié)果。( 對應(yīng) contract 里面的驗證屬性,下面會提到 。)
*/
async index() {
const { ctx } = this;
let result = await this.app.mysql.query(
'select * from user'
);
this.notFound()
}
async v1(){
const { ctx } = this;
ctx.body = "我是v1自動路由";
}
}
module.exports = HomeController;以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
從零開始學(xué)習(xí)Node.js系列教程四:多頁面實現(xiàn)的數(shù)學(xué)運算示例
這篇文章主要介紹了Node.js多頁面實現(xiàn)的數(shù)學(xué)運算,涉及nodejs請求響應(yīng)、數(shù)值傳遞、運算等相關(guān)操作技巧,需要的朋友可以參考下2017-04-04
Node.js創(chuàng)建一個Express服務(wù)的方法詳解
這篇文章主要介紹了Node.js創(chuàng)建一個Express服務(wù)的方法,結(jié)合實例形式分析了node.js創(chuàng)建Express服務(wù)的具體步驟、實現(xiàn)方法及相關(guān)操作技巧,需要的朋友可以參考下2020-01-01
node使用require?mkdirp創(chuàng)建文件夾示例
這篇文章主要為大家介紹了node使用require?mkdirp創(chuàng)建文件夾示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
express + jwt + postMan驗證實現(xiàn)持久化登錄
這篇文章主要介紹了express + jwt + postMan驗證實現(xiàn)持久化登錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06

