bulletproof-nodejs icon indicating copy to clipboard operation
bulletproof-nodejs copied to clipboard

CORS not working

Open wasifali opened this issue 5 years ago • 2 comments

I'm trying to add cors to express app right after setting it,

const app = express();
 
app.use(
    cors({
      origin: ['some_origin', 'some_origin_2'],
    }),
  );

expected behaviour is it should allow requests from 'some_origin' and 'some_origin_2' but instead both are still blocked.

wasifali avatar Dec 09 '20 12:12 wasifali

Hey, Try this , cause I think u must pass a function rather than an array

var allowedOrigins = ['http://localhost:3000',
                      'http://yourapp.com'];
app.use(cors({
  origin: function(origin, callback){
    // allow requests with no origin 
    // (like mobile apps or curl requests)
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
      var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  }
}));

KaidiMohammed avatar Dec 09 '20 14:12 KaidiMohammed

@KaidiMohammed This is working if we use callback function but it return Access-Control-Allow-Origin: * instead of Access-Control-Allow-Origin: http://domainname.com in request header.

arvindgemini avatar Dec 01 '21 11:12 arvindgemini