Parth
Parth

Reputation: 1

How to handle preflight CORS request using Node server?

I have configured CORs in my Node server like below.

var originsWhitelist = [
  'http://localhost:4200'     //this is my front-end url for development

];
var corsOptions = {
  origin: function(origin, callback){
        console.log(origin);
        var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
        console.log(isWhitelisted);
        callback(null, isWhitelisted);
  },
  credentials:true
}

app.use(cors(corsOptions))

And I am sending json data from Angular frontend, but during that I am getting error like this, OPTIONS http://localhost:30000/api/addProfile 0 ()

And My request header is,

Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36

So, I have other post request in which I am sending multipart/from data but it works fine while this request sends error and response is unknown error.

Upvotes: 0

Views: 10952

Answers (1)

kkkkkkk
kkkkkkk

Reputation: 7748

This should do it:

app.options('*', cors(corsOptions));

You should read the document: https://github.com/expressjs/cors#enabling-cors-pre-flight

Also this issue is quite weird to me, cause browser should not fire preflight for POST request. Maybe I am missing something about CORS.

Upvotes: 0

Related Questions