How to add a custom header in AJAX with pure javascript?

2

I'm using pure javascript to send an AJAX with the Access_token header with a key inside, because web-service requests this request ... but it's not going as I would like.

I want it to look like this:

Butit'sgettinglikethis:

Here's my function:     function function () {

var xmlhttp;

if (window.XMLHttpRequest){
  xmlhttp=new XMLHttpRequest();
}else{
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){

    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    }
 }

  xmlhttp.open("POST","https://www.asaas.com/api/v1/customers?name=Lucas",true);
  xmlhttp.setRequestHeader('Access_token', 'bdb4b600eee96f16bf118c617a65561eba06629525c07f6564b9531a38959468');
  xmlhttp.setRequestHeader('Content-Type', 'application/json');
  xmlhttp.onreadystatechange = handler;
  xmlhttp.send();

 }
    
asked by anonymous 08.08.2014 / 13:36

1 answer

1

From what I saw the headers are being passed correctly, I noticed that when you get some code other than type 2XX, for example 401, 404 or others, chrome displays the headers this way:

InthiswaytheheadersarelistedinAccess-Control-Request-Headers,buttheirvaluesarenotdisplayed.

Usingthesamefunctionagainstaserverthataccepts,withthesameheaderswehavealreadyreceivedadifferentanswer,thewayyouwantitasintheimagebelow:

In this case I believe you are not seeing the way you want because of the server, not because of your AJAX implementation.

Even in the browser issue raised by Rui Pimentel its implementation is normal, both in IE (7+) and in other browsers the setRequestHeader (header, value) method is used to change or add headers to requests.

Method documentation is available at:

07.09.2014 / 06:38