ofrendo
11/11/2016 - 1:43 PM

Node+Express: Allow CORS (backend + frontend)

Node+Express: Allow CORS (backend + frontend)

// Allow requests to come from other domains
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin); // just allow all origins
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});

// Frontend: This is also for passport node module (the x-www-form-urlencoded header is otherwise not needed)
function doRequest(url, method, jsonParams, callback) {
  var params = "";
  for (var key in jsonParams) {
    params += key + "=" + jsonParams[key] + '&';
  }
  // remove last "&"
  params = params.substring(0, params.length-1);
  var http = new XMLHttpRequest();
  http.open(method, url, true);
  http.withCredentials = true;
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.onreadystatechange = function() {//Call a function when the state changes.

      if (http.readyState == 4) {
        if (typeof callback === "function") {
          callback(http);
        }
      }
  }
  console.log(http);
  http.send(params);
}