【发布时间】:2019-12-25 09:53:39
【问题描述】:
我在尝试在 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 查看我的招摇 API 我得到这个错误: SyntaxError: Unexpected token u in JSON at position 0 在 JSON.parse() 我不知道我应该如何调试这个错误以及为什么会出现这个错误!
【问题讨论】:
-
这里可能是
logger: config.logger.enabled ? fastifylogger : undefined,执行JSON.parse(undefined)时抛出的错误