[英]How to load a YAML file with swagger-ui-express?
I have following problem - i am using swagger-ui-express and when i am not on developement env i am facing parsing issue with my swagger;我有以下问题 - 我正在使用 swagger-ui-express,当我不在开发环境中时,我的 swagger 面临解析问题;
{"message":"Parsing swagger document failed. SyntaxError: Unexpected token :"}
This is in my swagger.js:这是在我的 swagger.js 中:
const {developmentEnv} = config;
const swaggerFile = developmentEnv
? jsYaml.safeLoad(fs.readFileSync('./src/api/swagger.yml'))
: require('../../api/swagger.yml');
I think, problem is with require .我认为,问题在于require 。 Yaml seems to be problem here.
Yaml 似乎是这里的问题。 Can anybody help me with this please?
有人可以帮我吗?
The problem here is with requiring.yaml file.这里的问题是 require.yaml 文件。
The documentation clearly says,文件清楚地说,
To load your swagger specification yaml file you need to use a module able to convert yaml to json;
要加载 swagger 规范 yaml 文件,您需要使用能够将 yaml 转换为 json 的模块; for instance yamljs.
例如 yamljs。
Here is the link https://www.npmjs.com/package/swagger-ui-express#load-swagger-from-yaml-file这是链接https://www.npmjs.com/package/swagger-ui-express#load-swagger-from-yaml-file
For example, Try this, it works:例如,试试这个,它有效:
const express = require('express');
const path = require('path');
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath();
const YAML = require('yamljs');
const swaggerDocument = YAML.load('swagger-config.yaml');
console.log(swaggerDocument);
const swaggerJsonDocument = require('./swagger.json');
console.log(swaggerJsonDocument);
const app = express();
app.use(express.static(pathToSwaggerUi))
app.use(express.json());
app.use(express.static(path.join(__dirname, '../views')));
app.get('/', (req, res) => {
res.send(`Hello World!`);
});
app.listen(2000, console.log(`App Listening to port 2000`));
In your case, you could write the code like below by importing a module yamljs :在您的情况下,您可以通过导入模块yamljs来编写如下代码:
First of all do, npm install yamljs首先, npm 安装 yamljs
const swaggerFile = developmentEnv ? YAML.load('swagger-config.yaml') : require('./swagger.json');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.