Loopback: Cannot set custom Access-Control-Allow-Origin CORS header

Created on 13 Jul 2016  路  7Comments  路  Source: strongloop/loopback

According to the guidance in https://docs.strongloop.com/display/public/LB/middleware.json, the
cors.param.origin can also be a function:
_Can also be set to a function, which takes the request origin as the first parameter and a callback (which expects the signature err [object], allow [bool]) as the second._

How can this be the case if the file is a .JSON file?
Can't seem to override it (e.g. with a .JS file)

triaging

Most helpful comment

For future reference, create file middleware.local.js:

var whitelist = ['http://example1.com', 'http://example2.com'];
module.exports = {
  "initial": {
    "cors": {
      "params": {
        "origin": function (origin, callback) {
          if (whitelist.indexOf(origin) !== -1) {
            callback(null, true);
          } else {
            callback(new Error('Not allowed by CORS'));
          }
        }
      }
    }
  }
};

Restart server

All 7 comments

Hi @stephenwil
Here is how to configure it with some examples:
https://www.npmjs.com/package/cors#simple-usage-enable-all-cors-requests
Let me know if you need further assistance.

Hi,
I'm trying to override middleware.json with middleware.local.js to apply the similar solution as per the link above so thanks. If I achieve what I'm trying I will close the issue.

@stephenwil
Don't worry about closing the issue. If you still need further assistance, please let me know so I can help.

All done :-), via middleware.local.js

@stephenwil I'll try to configure cors. Can you share your solution, please.

For future reference, create file middleware.local.js:

var whitelist = ['http://example1.com', 'http://example2.com'];
module.exports = {
  "initial": {
    "cors": {
      "params": {
        "origin": function (origin, callback) {
          if (whitelist.indexOf(origin) !== -1) {
            callback(null, true);
          } else {
            callback(new Error('Not allowed by CORS'));
          }
        }
      }
    }
  }
};

Restart server

Sadly the solution posted still not working .
I created the file with a .production and I added my front end app url in the wishlist but it's not working.

I created two files .local and I left it empty and .production and I added this code.
Anyone can advice me what to do.

Was this page helpful?
0 / 5 - 0 ratings