Search code examples
javascriptxmlhttprequestapiary.ioapiary

Apiary Invalid Header


Im trying to send a request to the apiary API and the header is always invalid. The API expect charset as 'utf-8' which is correctly set in the code. At the inspector of the api website you can see that the request hast set charset as UTF-8... Why is the charset at the request in capital letters? how can i fix it?

var Request = new XMLHttpRequest();
Request.open('POST', 'URL');
Request.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); //utf-8!!!
Request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  //JSON stuff
};

Request.send(JSON.stringify(body));

Solution

  • It looks like XMLHttpRequest changes the charset to uppercase UTF-8 in this case when sending the request. When trying the request through the Apiary.io documentation, it keeps the charset for content type to lowercase utf-8 and says the request is valid. When I copy/paste the code example into Chrome's console and view the request that's made, it changes the charset uppercase, which says to be an invalid request.

    In the jQuery documentation on setting the charset, it says the following:

    The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

    In light of this, I tried to change the charset to something else and it still showed up as charset=UTF-8 in the request, so my initial thinking is that it will always be uppercase.