所以我试图为我的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
就像我说的,医生也是空的:
的
你知道可能是哪个原因/问题吗?或者我如何解决这个问题?谢谢!
1条答案
按热度按时间v8wbuo2f1#
我相信你的问题是你从哪里运行命令。如果你从项目的根运行命令,你的相对路径是不正确的。
字符串
这里有一个简单的回购
的数据