尝试在nodejs中实现swagger并收到错误代码406

e37o9pze  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(128)

我试图实现斯瓦格这里是代码设置

const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Nitin API',
      version: '1.0.0',
      description: 'API Documentation'
    },
    servers: [
      {
          url: 'http://localhost:8101/api/v1',
          description: 'Local server'
      },
    ],
    components: {
      securitySchemes: {
        JWTAuth: { // Define the Bearer Token (JWT) security scheme
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      }
    },
    security: [{
      JWTAuth: []
    }]
  },
  apis: ['src/api/core/routes/v1/*.ts'],
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);
// console.log("swaggerSpec", swaggerSpec);
const excludeSwagger = true;

if(excludeSwagger){
  // this.application.use('/api-docs', (req, res, next) => {
  //   req.headers['Content-Type'] = CONTENT_TYPE_ENUM['application/json'];
  //   next();
  // });
  this.application.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}

这是我正在实施的路线

/**
  • @swagger
  • /admin/get_all_user:
  • 职务:
produces:
- application/json
summary: Get all users.
description: Get a list of all users.
tags:
- Admin
security:
- JWTAuth: []  # Specify JWT as the authentication method
requestBody:
required: false  # Set to true if authentication is required
content:
application/json:
schema:
type: object
responses:
'200':
description: Successful response with a list of users.
content:
application/json:
schema:
type: array  # Adjust this based on the actual response structure
'401':
description: Unauthorized. JWT token is missing or invalid.
'500':
description: Internal server error.
  • / this.router.route('/get_all_user ').post(AuthService.authenticateToken,AdminController.getAllSubUserListForAdmin);

This is the page rendered after the implementation
API i am trying to hit
This has a body takes an empty object
The response i get after hitting the API route.
尽管CORS在代码中处理得很好,

private options: Record<string, unknown> = {
cors: {
  origin: (origin: string, callback: ( error: Error, status?: boolean ) => void) => {
    console.log(origin)
    if (AUTHORIZED.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback( notAcceptable('Domain not allowed by CORS') );
    }
  },
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  allowedHeaders: ['Accept', 'Content-Type', 'Authorization', 'Origin', 'From'],
  credentials: true,
},

为了进一步消除我使用的cors错误,

this.router.route('/get_all_user').post(AuthService.authenticateToken, AdminController.getAllSubUserListForAdmin, (req, res) => {
 res.setHeader('Access-Control-Allow-Origin', '*');

});
但我还是犯了同样的错误。也尝试过cors扩展。
我在这里做错了什么,任何帮助都非常感谢。

ttygqcqt

ttygqcqt1#

尝试查找环境文件,并尝试找到您正在命中的域。这可能会解决您的错误

相关问题