node.jsexpressswaggerswagger-uiswagger-jsdocs

Syntax error on swagger-jsdoc setup in nodejs


I am getting a syntax error on trying to set up swagger with my express app

I was trying to follow this tutorial here https://itnext.io/setting-up-swagger-in-a-node-js-application-d3c4d7aa56d4 as a quick start guide, I do not know why I am getting that error

This is my 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;

And here are my routes in ./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);
};

And one of the routes eg ./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;

I followed the instructions and my app should work instead I am getting a 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) error


Solution

  • In app.js, change definitions (plural) to definition (singular). swagger-jsdoc expects that the option containing the API definition be named either options.swaggerDefinition or options.definition.

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