Forum Discussion

MitulKheni's avatar
MitulKheni
Visitor
2 years ago

CORS error in swagger-ui

I am getting the error in the swagger UI: Possible cross-origin (CORS) issue? The URL origin (https://petstore.swagger.io) does not match the page (http://localhost:9000). Check the server returns the correct 'Access-Control-Allow-*' headers.

 

Following is the swagger.ts file:

import swaggerJSDoc from 'swagger-jsdoc';

const options = {
	failOnErrors: true,
	definition: {
		openapi: '3.0.0',
		info: {
			title: 'Boilerplate app',
			version: '1.0.0',
			description: 'Your API description',
		},
		servers: [{ url: 'http://localhost:9000' }],
	},
	apis: ['./src/api/**/*.ts'],
};

const swaggerSpec = swaggerJSDoc(options);

export default swaggerSpec;

I already have enabled the CORS in my app.ts file

'use strict';
import express from 'express';
import cors from 'cors';
import swaggerUi from 'swagger-ui-dist';
import router from './api/api.routes';
import swaggerSpec from './swagger';

const app = express();

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

app.use(cors());
app.options('*', cors());

app.use('/api-docs', express.static(swaggerUi.getAbsoluteFSPath()));
app.get('/api-docs.json', (req, res) => {
	res.setHeader('Access-Control-Allow', '*');
	res.setHeader('Access-Control-Allow-Methods', 'GET');
	res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

	res.send(swaggerSpec);
});

app.use(router);

export default app;