为什么我在访问应用的Swagger文档时会收到“No operations defined in spec!”消息?

83qze16e  于 10个月前  发布在  其他
关注(0)|答案(1)|浏览(445)

所以我试图为我的NodeJS应用程序设置Swagger,但我现在正在努力解决一个问题。我将尽可能详细地解释。
所以我有swagger.util.js文件:

import swaggerJSDoc from "swagger-jsdoc";

const options = {
    failOnErrors: true,
    definition: {
        openapi: "3.0.0",
        info: {
            title: "API",
            version: "1.0.0",
            description: "Endpoints"
        },
        servers: [
            {
                url: "http://localhost:80",
                description: "HTTP"
            },
            {
                url: "http://localhost:443",
                description: "HTTPS"
            }
        ],
    },
    apis: ["../routes/*.js"]
};

const specs = swaggerJSDoc(options);

export default specs;

字符串
这个user.route.js文件:

import express from "express";
import trimRequest from "trim-request";

import { register } from "../controllers/user.controller.js";

const router = express.Router();

/**
 * @swagger
 * components:
 *   schemas:
 *     UserAccount:
 *       type: object
 *       required:
 *         - username
 *         - email
 *         - password
 *       properties:
 *         username:
 *           type: string
 *         email:
 *           type: string
 *         password:
 *           type: string
 *       example:
 *         username: Test
 *         email: [email protected]
 *         password: TestTest1!
 */
router.route("/register").post(trimRequest.all, register);

export default router;


index.js中使用的app.js文件:

import compression from "compression";
import cookieParser from "cookie-parser";
import cors from "cors";
import dotenv from "dotenv";
import express from "express";
import mongoSanitize from "express-mongo-sanitize";
import helmet from "helmet";
import createHttpError from "http-errors";
import morgan from "morgan";
import swaggerUI from "swagger-ui-express";

import routes from "./routes/index.route.js";
import specs from "./utils/swagger.utils.js";

dotenv.config();

const app = express();

app.use(compression());
app.use(cookieParser());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));
app.use(helmet());
app.use(mongoSanitize());
if (process.env.ENV !== "prd") {
    app.use(morgan("dev"));
}
app.use("/docs", swaggerUI.serve, swaggerUI.setup(specs));
console.log(specs);

// Remove this later
app.get("/", (_req, res) => {
    res.send("Hello");
});

app.use("/api/v1", routes);

app.use(async (_req, __res, next) => {
    next(createHttpError.NotFound("This route does not exist"));
});

app.use(async (err, _req, res,_next) => {
    res.status(err.status || 500);
    res.send({
        error: {
            status: err.status || 500,
            message: err.message,
        },
    });
});

export default app;


文件夹结构如下:

-src
 -controllers
  -user.controller.js
 -routes
  -index.route.js
  -user.route.js
 -utils
  -swagger.utils.js
 -app.js
 -index.js


问题是app.js中的console.log(specs);由于某种原因返回了一个组件字段为空的json(空对象)。但它应该返回一些东西,因为我在user.route.js中有JSDoc注解,对吗?x1c 0d1x
就像我说的,医生也是空的:



你知道可能是哪个原因/问题吗?或者我如何解决这个问题?谢谢!

v8wbuo2f

v8wbuo2f1#

我相信你的问题是你从哪里运行命令。如果你从项目的根运行命令,你的相对路径是不正确的。

const options = {
    definition: {

        openapi: '3.0.3',
        info: {
            title: 'test',
            version: '1.0.0'
        },
        servers: [
            { url: 'https://www.example.com/v1' }
        ]
    },
    apis: [
        'src/routes/user.route.js'  // <<< this can't use a relative ref. 
    ]
}

字符串
这里有一个简单的回购

📦src
 ┣ 📂routes
 ┃ ┗ 📜user.route.js
 ┣ 📂utils
 ┃ ┗ 📜openapi.util.js
 ┗ 📜index.js
// index.js
import express from 'express'
import swaggerUI from 'swagger-ui-express'
import OASdescription from './utils/openapi.util.js'

const app = express()
app.use(express.json())
const PORT = process.env.PORT || 3000

app.use('/api/docs', swaggerUI.serve, swaggerUI.setup(OASdescription))

app.listen(PORT, () => console.log(`listening on port ${PORT}`))
// openapi.util.js
import swaggerJsdoc from 'swagger-jsdoc'

const options = {
    definition: {

        openapi: '3.0.3',
        info: {
            title: 'test',
            version: '1.0.0'
        },
        servers: [
            { url: 'https://www.example.com/v1' }
        ]
    },
    apis: [
        'src/routes/user.route.js'
    ]
}

const OASDescription = swaggerJsdoc(options)

export default OASDescription
// user.route.js
import { Router } from 'express'

const router = Router()

/**
* @openapi
* '/user':
*   get:
*     description: my hosted api docs
*     summary: api docs
*     responses:
*       '200':
*         description: OK
*         content:
*           'application/json':
*             schema:
*               type: object
*               properties:
*                 thing:
*                   $ref: '#/components/schemas/UserAccount'
* components:
*   schemas:
*     UserAccount:
*       type: object
*       required:
*         - username
*       properties:
*         username:
*           type: string
*/
router.get('/user', (req, res) => {

    res.status('200').json({ "username": "test" })
})

export default router


的数据

相关问题