现有的nodeJS和swagger JS文档不起作用

问题描述 投票:0回答:1

我有一个简单的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: "[email protected]"
      },
      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定义。enter image description here有人可以帮我吗?

Grz,皮特

node.js swagger-ui swagger-jsdocs
1个回答
0
投票

在项目中添加招摇非常简单。只需执行以下步骤:-

安装模块“ swagger-ui-express”

npm install swagger-ui-express

在您的app.js文件中添加:-

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

创建swagger.json文件(我已经添加了简单的登录API和类)看起来像:-

{
    "swagger": "2.0",
    "info": {
      "version": "1.0.0",
      "title": "Parveen App API",
      "description": "Find out how your APIs work",
      "license": {
        "name": "MIT",
        "url": "https://opensource.org/licenses/MIT"
      }
    },
    "host": "localhost:5000",
    "basePath": "/api/v1",
    "tags": [
      {
        "name": "Users",
        "description": "API for users in the system"
      }

    ],
    "schemes": [
      "http",
      "https"
    ],
    "consumes": [
      "application/json"
    ],
    "produces": [
      "application/json"
    ],
    "securityDefinitions": {
        "ApiKeyAuth":{
          "type": "apiKey",
          "in": "headers",
          "name": "authorization"
        }
    },
    "paths": {
      "/users/login": {
        "post": {
          "summary": "Login user",
          "tags": [
            "Users"
          ],
          "description": "Login user in system",
          "parameters": [
            {
              "name": "user",
              "in": "body",
              "description": "Login user",
              "schema": {
                "$ref": "#/definitions/User"
              }
            }
          ],
          "produces": [
            "application/json"
          ],
          "responses": {
            "200": {
              "description": "Login Success",
              "schema": {
                "$ref": "#/definitions/User"
              }
            },
            "401":{
              "description": "Login details are not valid!!"
            },
            "404":{
              "description": "Email is not registered!"
            },
            "500":{
              "description": "User login failed!!"
            }
          }
        }
      }
    },

    "definitions": {

      "User": {
        "properties": {
          "email": {
            "type": "string"
          },
          "password": {
            "type": "string"
          }
        }
      },
      "userEmail":{
        "properties": {
          "email": {
            "type": "string"
          }
        }
      }



    }
  }

您可以根据您的API添加/更改swagger.json。

现在只需打开http://localhost:5000/api-docs

它将像冠军一样工作!

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.