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;
{"message":"Parsing swagger document failed. SyntaxError: Unexpected token :"}
This is in my 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. Yaml seems to be problem here. Can anybody help me with this please?
The problem here is with requiring .yaml file.
The documentation clearly says,
To load your swagger specification yaml file you need to use a module able to convert yaml to json; for instance yamljs.
Here is the link 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:
First of all do, npm install yamljs
const swaggerFile = developmentEnv ? YAML.load('swagger-config.yaml') : require('./swagger.json');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With