4

Is it a good practice to use setRequestHeader twice like below? I need to use X-Requested-With in order to get some HTML forms.

function formRequest (method, url) {
  return new Promise(function (resolve, reject) {
    var client = new XMLHttpRequest();
    client.open(method, url);
    client.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    client.setRequestHeader('Content-Type', 'text/html');
    client.onload = function () {
      // ...
      resolve(client.response);
    };
    // ...
    client.send();
  });
}

Thank you.

By the way, it works with or without the Content-type.

2
  • js at Question appears to return expected result? Commented Jun 4, 2016 at 23:53
  • 3
    You can add as many request headers you need, there is nothing wrong with it Commented Aug 6, 2017 at 9:23

1 Answer 1

7

request.setRequestHeader() Can be called multiple times, each time it is called it will add a new header. Therefore what you have done in your question is correct.

client.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
client.setRequestHeader('Content-Type', 'text/html');

Will cause your request to have two headers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.