Reputation: 33428
How can I set the correct Accept HTTP header for requesting another Media Type (in this case as Html) with GitHub's API? The current content object
is always encoded as base64, but I need it as rendered html: application/vnd.github.VERSION.html+json
.
$.ajax({
url: "https://api.github.com/repos/jquery-boilerplate/patterns/readme",
headers: {
Accept: "application/vnd.github.v3.html+json"
},
dataType: 'jsonp',
success: function (data) {
console.log(data.data.content); // "IyNSZWN..."
},
error: function (error) {
console.log(error);
}
});
I've also tried to use jQuerys beforeSend
, no success:
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Accept", "application/vnd.github.v3.html+json");
}
So the Question:
Is it possible to get the rendered html without decoding the content:
decodeURIComponent(
window.escape(
window.atob(
data.data.content.replace(/[^A-Za-z0-9\+\/\=]/g, "")
)
)
)
and parsing it later during a markdown parser?
Upvotes: 1
Views: 1008
Reputation: 18782
You are using dataType: "jsonp"
. JSONP works by inserting <script>
tags into the document in order to load data from another domain. And since a <script>
tag works by just sending a GET request to the URL, without giving you the ability to set headers -- your Accept
header is being ignored (you can verify that in the developer tools of the browser you are using). And since your header is being ignored, it is given the default value of Accept: */*
, which loads encoded data.
The solution is not to use JSONP (dataType: "jsonp"
), rather just use JSON (dataType: "json"
). This will then force jQuery not to use <script>
tags, but XHR. However, using XHR will throw an error since the data is on another domain and you will be violating the same origin policy. To get around that, set up an OAuth application with GitHub for the domain you are making requests from (your website that is making the requests), which will enable you to make cross-origin requests with the JSON dataType (this works by passing CORS headers). Read more about this here:
http://developer.github.com/v3/#cross-origin-resource-sharing
Upvotes: 1