qwe asd
qwe asd

Reputation: 1658

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?

Upvotes: 0

Views: 499

Answers (2)

apsillers
apsillers

Reputation: 116050

application/json is a non-simple value for the Content-type request header (see the beginning of "Non-simple request" in my answer on How does Access-Control-Allow-Origin header work?, so it must be explicitly allowed by the server via the response header Access-Control-Allow-Headers: application/json. Simply add the line

res.header("Access-Control-Allow-Headers", "application/json");

to your server code.

Upvotes: 0

Anthony C
Anthony C

Reputation: 2157

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();
});

Upvotes: 1

Related Questions