John Glabb
John Glabb

Reputation: 1621

How to solve CORS issue in swagger-ui-express

I'm getting "Possible cross-origin (CORS) issue?" error for Spec2 when run this swagger-ui-express app:

const express = require('express');
var cors = require('cors');
const app = express();
const swaggerUi = require('swagger-ui-express');

var options = {
  explorer: true,
  swaggerOptions: {
    urls: [
      {
        url: 'http://petstore.swagger.io/v2/swagger.json',
        name: 'Spec1'
      },
      {
        url: 'http://xxx.xxx.xxx.xxx:xxxxx/swagger.json',
        name: 'Spec2'
      }
    ]
  }
}

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));

app.listen(8080, () => console.log(`Listening on port 8080!`))

Neither app.use(cors()) nor app.use(swaggerUi.cors()) helps. How can it be fixed?

Upvotes: 0

Views: 7874

Answers (2)

obax
obax

Reputation: 88

I am not sure if this is exact problem you are facing, but the following solution has fixed my issue.

I was using a fetch on an endpoint and the error suggested that the received request has an origin (header) of value null.

I have set up a request interceptor to add an origin header on the request. Example

app.get("/docs", swaggerUi.setup(null, {
    swaggerOptions: {
        requestInterceptor: function(request){
            request.headers.Origin = `http://localhost:3000`;
            return request;
        },
        url: `http://localhost:3000/docs/api-doc`
    }
}))

Upvotes: 2

Arun Prasat
Arun Prasat

Reputation: 360

check the link which gives the way to overcome the issue. Also, you can install CORS plugin in chrome if you want and try it.

Upvotes: 0

Related Questions