Node.js Express Cors

If you need to request data from a server in a different domain, you need Jsonp or Cors. Jsonp is slower than Cors. In this example, I’ll show you how to use Cors with Node.js

This is CORS
[js]
var Cors = {
xhr: "",
url: "http://example.com/",
init: function(){
this.createCORSRequest(‘GET’, this.url);

if (this.xhr) {
this.onload();
this.onerror();
this.xhr.send();
}else{
//alert("not support");
//throw new Error(‘CORS not supported’);
}
},
createCORSRequest: function(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}

this.xhr = xhr;
},
onload: function(){
var self = this;
self.xhr.onload = function() {
var responseText = self.xhr.responseText;
console.log(responseText);
};
},
onerror: function(){
var self = this;
self.xhr.onerror = function() {
console.log("Cors error");
};
}
};
[/js]

This is Node.js part
[js]
exports.yourFunction = function(req, res) {
res.header(‘Access-Control-Allow-Origin’, "*");
res.header(‘Access-Control-Allow-Methods’, ‘POST,GET’);
res.header(‘Access-Control-Allow-Headers’, ‘content-Type,x-requested-with’);

console.log(req.params);
res.send("", 200);
}
[/js]