Search code examples
ajaxxmlhttprequestcors

Request header field Access-Control-Allow-Origin


I have expressjs server which runs on http://localhost:3000

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});

and client app http://localhost:8080 and would like to post data to the server. I use XMLHttpRequest:

execute(url, requestType, params) {
  return new Promise(
    (resolve, reject) => {
      var request = new XMLHttpRequest();
      request.open(requestType, url, true);
      request.setRequestHeader('Accept', 'application/json');
      request.setRequestHeader('Content-Type', 'application/json');
      request.onload = () => {
       switch (request.status) {
        case 201:
        case 200:
          resolve(request.response);
          break;
        default:
          reject(`${Constants.ERRORS.NETWORK}: ${request.statusText}`);
          break;
       }
   }

   request.onerror = () => {
      reject(Constants.ERRORS.NETWORK);
   };

   params ? request.send(params) : request.send();
  });

};

And when I use execuete("http://localhost:3000/register", "POST", {"some": "data"}), I have error Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. How can I fix it?


Solution

  • I had a similar issue before and fixed by using

    app.all('/', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      next();
    });
    

    or

    app.all('*', function(req, res, next) {
          res.header("Access-Control-Allow-Origin", "*");
          res.header("Access-Control-Allow-Headers", "X-Requested-With");
          next();
    });