我有一个简单的 nodeJS 项目,想在其中添加招摇。我需要 swaggerUI 和 swaggerJSDoc
这是我的 app.js 文件。
// requires
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const postsRoutes = require("./routes/posts/posts");
const userRoutes = require("./routes/auth/user");
const swaggerUi = require("swagger-ui-express");
const swaggerJSDoc = require("swagger-jsdoc");
// https://swagger.io/specification/v2/
const swaggerOptions = {
swaggerDefinition: {
info: {
title: "Post API",
description: "This is a sample Post API",
contact: {
name: "Test ",
url: "http://www.swagger.io/support",
email: "test@gmail.com"
},
servers: ["http://localhost:3850/"]
}
},
swagger: "2.0",
apis: ["/backend/routes/posts/posts.js"]
};
const app = express();
let options = {
explorer: true
};
// swagger
const swaggerDocs = swaggerJSDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs, options));
// MONGOOSE CONNECT
mongoose
.connect(
"mongodb+srv://"
)
.then(() => {
console.log("####-connected to MongoDB");
})
.catch(error => {
console.log("Connection ERROR!", error);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join("backend/images")));
// CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
// ROUTES
app.use("/api/posts", postsRoutes);
app.use("/api/user", userRoutes);
module.exports = app;
我有几条路线,还有一个 post.js 路线文件。该文件包含在数组中,定义为 swagger。
// express router
const router = express.Router();
// get posts endpoint
/**
* @swagger
* /api/posts:
* get:
* description use to request all posts
* responses:
* '200':
* description: a successful response
*/
router.get("", PostController.getPosts);
不幸的是,我在浏览器中没有看到任何 api 定义。 有人可以帮助我吗?
格兹,皮特