gonephishing gonephishing - 6 months ago 61
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

var port = process.env.PORT || 10010;

if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl' + 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');


  1. Adding CORS using statements given in enable-cors website:

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


I guess you have not configure cors properly.

npm install cors


var cors = require('cors');


See more

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