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

Asked

Viewed 1,087 times

3

I am using pure javascript to send an AJAX with the Access_token header with a key inside, because the web-service asks for this request... but it is not going as I would like.

I want you to stay like this:

Ajax como eu quero

But it’s getting like this:

inserir a descrição da imagem aqui

It follows 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();

 }
  • Which browser are you trying from? Is your app’s domain the same as the requested resource? And finally, you could provide the source of the request and response?

1 answer

1


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

Requisição 401

This way the headers are listed in Access-Control-Request-Headers, but their values are not displayed.

Using the same function against a server that accepts, with the same headers we have already received a different response, the way you want as in the image below:

inserir a descrição da imagem aqui

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

Even in the question of browsers 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.

The method documentation is available at:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.