Search code examples
javascriptnode.jsexpressswagger-ui

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?


Solution

  • 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`
        }
    }))