0

我在尝试在 nodejs 应用程序上设置 swagger 时遇到语法错误。我使用 node 的 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 来查看我的 swagger API 时,我得到了这个错误:SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () 我不知道我应该如何调试这个错误以及为什么会发生此错误!

4

1 回答 1

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}`)
于 2019-12-25T10:12:58.693 回答