在nodejs中设置swagger-jsdoc的语法错误

时间:2019-07-10 10:22:18

标签: node.js express swagger swagger-ui swagger-jsdocs

在尝试使用我的Express应用设置招摇时出现语法错误

我正尝试在此处https://itnext.io/setting-up-swagger-in-a-node-js-application-d3c4d7aa56d4上学习本教程,作为快速入门指南,我不知道为什么会收到该错误

这是我的app.js

import 'regenerator-runtime/runtime';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import swaggerUI from 'swagger-ui-express';
import swaggerJSDocs from 'swagger-jsdoc';
import allRoutes from './routes';


const definitions = {
  info: {
    // API information (required)
    title: 'Wayfarer', // Title (required)
    version: '1.0.0', // Version (required)
  },
  securityDefinitions: {
    bearerAuth: {
      type: 'apiKey',
      name: 'Authorization',
      scheme: 'bearer',
      in: 'header',
    },
  },
};

const options = {
  definitions,
  apis: ['./routes/index.js'],
};

const swaggerSpec = swaggerJSDocs(options);

const app = express();

app.get('/swagger.json', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
});
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
app.use(cors());
app.use(bodyParser.urlencoded({
  extended: true,
}));
app.use(bodyParser.json());

allRoutes(app);

export default app;

这是我在./routes/index.js的路线

import userRouter from './users';
import busRouter from './buses';
import tripRouter from './trips';

const versionNumber = '/api/v1';

export default (app) => {
  app.use(versionNumber, userRouter);
  app.use(versionNumber, busRouter);
  app.use(versionNumber, tripRouter);
};

其中一条路线,例如./routes/users

import router from './router';
import userMiddleware from '../middleware/users';

router.post('/auth/signup', userMiddleware.signupClients(), userController.signUp.bind(userController));

router.post('/auth/signin', userMiddleware.signinClients(), userController.signinClients.bind(userController));

router.post('/auth/signin/admin', userMiddleware.signinAdmin(), userController.signinAdmin.bind(userController));

export default router;

我按照说明进行操作,我的应用程序应该可以运行,但出现Error: SyntaxError: Unexpected token u in JSON at position 0 at module.exports (/home/frank/Desktop/Web Dev/Git projects/Way-Farer/node_modules/swagger-jsdoc/lib/index.js:32:11) at Object.<anonymous> (/home/frank/Desktop/Web Dev/Git projects/Way-Farer/api/src/app.js:32:21)错误

1 个答案:

答案 0 :(得分:0)

在app.js中,将definitions(复数)更改为definition(单数)。 swagger-jsdoc expects,将包含API定义的选项命名为options.swaggerDefinitionoptions.definition

const definition = {  // <-----
  ...
};

const options = {
  definition,      // <-----
  apis: ['./routes/index.js'],
};