Permissive CORS check in meanjs.org application during development?

Issue

I am using meanjs.org stack to develop a simple application. Now I am working on the mobile client with ionic framework.

Current issue I have is the CORS check causes an error when testing the ionic app like is described here: http://blog.ionic.io/handling-cors-issues-in-ionic/. While I could set up a proxy as described in that link it also works if I add the response header to the server side like: res.header("Access-Control-Allow-Origin", "*");

Adding this to each endpoint doesn’t feels good and I would like to find a solution to use during development where I could disable the CORS check.

I’ve also tried changing the lusca configuration on config/env/default.js setting xssProtection: false bit didn’t work?

How can I, during development, enable the following response header res.header("Access-Control-Allow-Origin", "*"); in all endpoints, is it possible or the only viable solution using meanjs.org + Ionic during development is setting up the proxy?

Solution

After some time I finally got a hint on the meanjs.org forums and built a solution.

Create the following method on config/lib/express.js file:

/**
 * Disable CORS check to be used during development with access from mobile clients (currently tested with ionic)
 */
module.exports.disableCORSForDev = function(app) {
  app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'POST');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  }).options('*', function(req, res) {
    res.end();
  });
  var corsOptionsDelegate = function(req, callback) {
    var corsOptions = { credentials: true };
    callback(null, corsOptions); // callback expects two parameters: error and options
  };
  app.use(cors(corsOptionsDelegate));
};

added the following to the method init on this same class just after declaration of var app = express();

var app = express();

this.disableCORSForDev(app);

Note: This is a server side solution to bypass cors during development and should not be used in production, many may prefer to setup a proxy on the ionic client instead as it’s described in this ionic article.

Answered By – groo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published