目标:在本文中,您将知道如何创建nodejs服务器,连接Swagger
先决条件在完成本文之前,您应该已经安装了所有先决条件工具,包括:Visual Studio Code,Node Package Manager(NPM),节点。
第一步:项目开始
npm init -y
然后安装其他插件
npm i express swagger-ui-express yamljs
也安装Dev依赖项
npm i -D nodemon
配置package.json
文件
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
创建一个已经安装的index.js
文件和导入必要的插件。
const express = require('express')
const swaggerUI = require('swagger-ui-express')
const YAML = require('yamljs')
const swaggerDoc = YAML.load('./swagger.yaml')
创建Express Server,并将几件事配置为index.js
文件
//express app
const app = express()
app.use(express.json())
app.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerDoc))
app.get('/health', (_req, res) => {
res.status(200).json({
health: 'Ok'
})
})
app.listen(4000, ()=> {
console.log('Server is listening on port 4000')
} )
创建swagger.yaml
文件。插入此基本文件的位置。
openapi: 3.0.0
info:
version: 1.0.0
title: Testing Open Api Spec
description: >
I am learning Open API Specification. This is industry standard specification technique for any web service
termsOfService: https://example.com/terms
contact:
name: Bipon Biswas
url: https://example.com
email: support@gmail.com
license:
name: Apache 2.0
url: http://apache.com
servers:
- url: http://localhost:4000/api/v1
description: dev server
- url: http://example.com/api/v1
description: prod server
paths:
/health:
get:
tags: [Health]
description: this endpoint will test the health of the api
responses:
'200':
description: it will return a success message
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: ok
'500':
description: The Server is down
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: server is down
现在运行项目
npm run dev
现在将URL打入浏览器http://localhost:4000/health
还击中url http://localhost:4000/docs/
参考