Search code examples
javascriptajaxxmlhttprequestgithub-api

Can't set header using Github API from Javascript


I'm using javascript's XMLHttpRequest to receive data from Github API and I am trying to use the custom media type specification but can't get it to work. Setting the Accept header doesn't change the format of the response at all. The result I get is always the default (JSON).

This is the code I'm using to make the request:

var url = "https://api.github.com/repos/mrdoob/three.js/issues/comments/241553390";
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader("Accept", "application/vnd.github.v3.raw");
xhr.setRequestHeader("Content-Type","application/vnd.github.v3.raw");
xhr.onload = function(ev) {
    console.log("Response:", ev.target.response);
    console.log("Headers:", xhr.getAllResponseHeaders());
};
xhr.send();

Solution

  • The response JSON contains a "body" attribute.

    I tried changing the version from raw to other types and noticed that only the "body" attribute changes. Did I understand your question wrong? What other types of response does GitHub API support? xhr.setRequestHeader("Accept", "application/vnd.github.v3.html"); results in "body_html" while xhr.setRequestHeader("Accept", "application/vnd.github.v3.html"); results in "body"

    JSFiddle here - https://jsfiddle.net/3yqutj29/4/