4

I generated my server code (nodejs-server) based on the swagger specification I have.

The problem is that when I try to hit the API from my UI (different domain), I'm getting the well know error that CORS is not enabled:

XMLHttpRequest cannot load http://127.0.0.1:10010/events. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

My generated index.js is as follows:

'use strict';

var fs = require('fs'),
    path = require('path'),
    http = require('http');

var app = require('connect')();
var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');
var serverPort = 10010;

// swaggerRouter configuration
var options = {
  swaggerUi: path.join(__dirname, '/swagger.json'),
  controllers: path.join(__dirname, './controllers'),
  useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {

  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // Validate Swagger requests
  app.use(middleware.swaggerValidator());

  // Route validated requests to appropriate controller
  app.use(middleware.swaggerRouter(options));

  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi());

  // Start the server
  http.createServer(app).listen(serverPort, function () {
    console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
    console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort);
  });

});

Not sure how I can enable CORS using this generated code.

amp
  • 11,754
  • 18
  • 77
  • 133

1 Answers1

10

add this code above 'Initialize the Swagger middleware', changing the domain to the correct one. The node code comes from jvandemo's answer to same question No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

// Add headers
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://server.to.allow.access.from');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

// Pass to next layer of middleware
next();
});

swagger-codegen wont overwrite an existing index.js

[main] INFO io.swagger.codegen.DefaultCodegen - 
Skipped overwriting index.js as the file already exists in 
C:\path\to\swagger-codegen\generated\nodejs\index.js
Community
  • 1
  • 1
Brendan Doherty
  • 148
  • 2
  • 6
  • Thanks, this solved the problem. BTW, do you use the swagger code generator? Do you think is a useful tool? Specially the `nodejs-server` code... If you have any material, resource, tutorial that helps to use it, let me know. It will be highly appreciated. – amp May 17 '17 at 12:23
  • 1
    I use swagger-code gen to mock the API responses while I am waiting for java backend guys to do their bit. If you use swagger to define the API then the ability to mock the back is just an added extra for me. – Brendan Doherty May 24 '17 at 14:15