gonephishing gonephishing - 3 months ago 37
Node.js Question

Enabling Cross Origin Resource sharing (CORS) in ExpressJS framework on NodeJS developed using Swagger

I've hosted a nodejs server on localhost generated using Swagger and I'm trying to make API calls to it using Swagger UI again hosted on localhost. The network profile in chrome is showing connection refused everytime I'm making a call because CORS header are not added to the request.

This is my app.js file which was generated using Swagger:

'use strict';

var SwaggerExpress = require('swagger-express-mw');

var app = require('express')();
module.exports = app; // for testing

var config = {
appRoot: __dirname // required config
};


SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }

// install middleware

swaggerExpress.register(app);
var port = process.env.PORT || 10010;
app.listen(port);

if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});


Till now I've tried the following methods and none of them has worked:


  1. Importing cors module from npm:

    npm install cors




In app.js

var cors = require('cors');

app.all(cors())




  1. Adding CORS using statements given in enable-cors website:
    http://enable-cors.org/server_expressjs.html



Both the above methods have failed for me, what can I try next? I can share more code samples if required.

Answer

I guess you have not configure cors properly.

npm install cors

Usage

var cors = require('cors');

app.use(cors());

See more

CORS Support https://github.com/swagger-api/swagger-ui#cors-support