nodejs上的swagger congif的SyntaxError固定

时间:2019-12-25 09:53:39

标签: node.js swagger fastify

我在尝试在Node.js应用上设置摇摇欲坠时遇到语法错误。我为节点使用fastify框架。我的配置基于本教程how-to-build-blazing-fast-rest-apis-with-node-js-mongodb-fastify-and-swagger

这是我的server.js:

const swagger = require('./main/config/swagger')
const routes = require('./main/routes/v1')
const config = require('./main/config')


const fastifylogger = {
  level: config.logger.level,
  file: config.logger.file,
  serializers: {
    res: (res) => ({
     statusCode: res.statusCode,
     request: res.input,
     payload: res.payload,
}),
},
} 
const fastify = require('fastify')({
 logger: config.logger.enabled ? fastifylogger : undefined,
 pluginTimeout: 1000,
})
fastify.register(require('fastify-swagger'), swagger.options)
fastify.ready(() => {
console.log('fastify server is ready')
fastify.swagger()
})

fastify.listen(config.server.port, '0.0.0.0')

这是swagger.js文件:

exports.options = {
 routePrefix: '/documentation',
 exposeRoute: true,
 swagger: {
 info: {
  title: 'Fastify API',
  description: 'Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger',
  version: '1.0.0',
},
externalDocs: {
  url: 'https://swagger.io',
  description: 'Find more info here',
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
},
}

但是当我转到此url:localhost:3002 / documentation以查看我的灵活API时,出现以下错误: SyntaxError:JSON中位置0处的意外令牌u     在JSON.parse() 我不知道该如何调试此错误以及为什么会发生此错误!

1 个答案:

答案 0 :(得分:0)

我猜是comma-dangle
https://eslint.org/docs/rules/comma-dangle

我建议检查您的swagger.js

exports.options = {
    routePrefix: '/documentation',
    exposeRoute: true,
    swagger: {
        info: {
            title: 'Fastify API',
            description: 'Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger',
            version: '1.0.0'
        },
        externalDocs: {
            url: 'https://swagger.io',
            description: 'Find more info here'
        },
        host: 'localhost',
        schemes: ['http'],
        consumes: ['application/json'],
        produces: ['application/json']
    }
}

测试一下。

fastify.register(require('fastify-swagger'), {
    routePrefix: '/documentation',
    exposeRoute: true,
    swagger: {
        info: {
            title: 'Fastify API',
            description: 'Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger',
            version: '1.0.0'
        },
        externalDocs: {
            url: 'https://swagger.io',
            description: 'Find more info here'
        },
        host: 'localhost',
        schemes: ['http'],
        consumes: ['application/json'],
        produces: ['application/json']
    }
});

最后一次尝试...

// move .swagger() code
// move under line `listen`

await fastify.listen(3000)
fastify.swagger()
fastify.log.info(`listening on ${fastify.server.address().port}`)