'Express cors get origin = 'null' with type string
Express CORS is failing for my nodejs application and I need your help fixing it. The reason is that the app is getting null with type string as origin, which is not in my list of whitelisted domain. If I whitelist null, it works but I am not sure it should be that way. The problem occurs in both dev (Windows) and prod (Ubuntu+nginx) mode.
Here is my CORS config:
{
  origin: function (origin, callback) {
    //console.log(typeof origin)
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      return callback(null, true)
    } else {
      logger.warn('origin ' + origin + ' is not whitelisted')
      return callback(new Error('Not allowed by CORS'), false)
    }
  }
}
The problem goes away if I add set the Access-Control-Allow-Origin header like the following but that seems to defeat the purpose of CORS.
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
One thing to mention, I never had such issue when developing NodeJS API. This project has an integrated view engine. I don't know whether it is related or not.
Thank you in advance
Solution 1:[1]
Your corsConfig should look something like this;
{
origin: (origin, callback) => {
    if (!origin || origin === 'null') return callback(null, true);
    if (originsURL.indexOf(origin) === -1) {
        logger.warn('origin ' + origin + ' is not whitelisted')
        return callback(new Error('Not allowed by CORS'), false);
    }
    return callback(null, true);
    }
}
- If the origin is null or undefined, it should return the callback.
- If the origin is not within the allowed origins, callback returns an error.
- else return the callback.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Rida | 

