I have a simple nodeJS project and want to add swagger into it. I have required swaggerUI and swaggerJSDoc
Here is my app.js file.
// 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;
I have a couple of routes, also a post.js route file. This file is included in the array, with the definition of 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);
Unfortunately I don't see any api definition in the browser.
Can somebody help me?
Grz, Pete