ExpressJS + Swagger
npm init -y
npm install express swagger-ui-express
npm install --save-dev swagger-autogen
create app.js file
const express = require('express');
const app = express();
const port = process.env.port || 3000;
/*Swagger configurations start*/
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
/*Swagger configurations end*/
app.get('/', (req, res) => {
res.send('Nice to meet you!');
});
app.get('/products', (req, res) => {
const products = [
{
id: 1,
name: "hammer",
},
{
id: 2,
name: "screwdriver",
},
{
id: 3,
name: "wrench",
},
];
res.json(products);
});
app.listen(port, () => {
console.log(`app is running on http://localhost:${port}`);
});
create swagger.js file
const swaggerAutogen = require('swagger-autogen')();
const path = require('path');
const doc = {
info: {
title: 'SM Tool API'
}
};
const outputFile = path.join(__dirname, './swagger.json');
const endpointFiles = ['./app.js'];
swaggerAutogen(outputFile, endpointFiles, doc);
generate swagger.json file
node swagger.js
run app
node app.js
check results on http://localhost:3000/api-docs
创建时间:8/9/2022 2:01:12 PM
修改时间:10/25/2022 3:47:48 PM