Can't set header using Github API from Javascript - 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();

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/

You are requesting comments, which are all returned as JSON which you can use the media type to specify the body markdown. See: https://developer.github.com/v3/media/#comment-body-properties
The application/vnd.github.v3.raw is used for requesting a binary blob.

Related

XHR Post for saving document.body JS

i need to post document.body.innerHTML to my domain's proxy. There is working PM2 and before it I used GET and it looked like:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://domain.ru/pmproxy?info='+document.body.innerHTML+'&location='+document.location+1);
xhr.send();
Now, because there is a limit of letters I need to us POST. How can I turn this into POST?
First make sure the receiving server method accepts post and if you want to send data in xhr post you can do like this
xhr.send("info='+document.body.innerHTML+'&location='+document.location+1")
or if a server accepts a json object then you can use xhr.send(document.getElementById('#form).serialize());
You should convert it to this:
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://domain.ru/pmproxy');
xhr.send('info='+document.body.innerHTML+'&location='+document.location+1);
Also, I suggest you clean both parameters, so you can avoid problems in the future:
xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location+1));
Furthermore, I don't really know why you're using document.location+1, but you can use document.location.href and save the +1 so your code looks cleaner:
xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location.href));

How to read png meta data from JavaScript?

My custom server embeds meta data about an image in the PNG meta data fields. The image is loaded via a regular img tag. I'd like to access the meta data from JavaScript - any way to achieve this?
If not, what are the alternatives for serving additional information for an image? The images are generated on the fly and are relatively expensive to produce, so I'd like to serve the meta data and the image data in a single round trip to the server.
i had a similar task. I had to write physical dimensions and additional metadata to PNG files. I have found some solutions and combined it into one small library.
png-metadata
it could read PNG metadata from NodeJS Buffers, and create a new Buffers with new metadata.
Here how you can read PNG metadata in the Browser:
function loadFileAsBlob(url){
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
resolve(this.response);
// myBlob is now the blob that the object URL pointed to.
}else{
reject(this.response);
}
};
xhr.send();
})
};
const blob = await loadFileAsBlob('1000ppcm.png');
metadata = readMetadataB(blob);
A couple of solutions I can think of:
Pass the metadata as headers, use XMLHttpRequest to load the image and display it by converting the raw bytes to a data uri, as talked about here. Looks roughly like this:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var metadata = xhr.getResponseHeader("my-custom-header");
image.src = window.URL.createObjectURL(xhr.response);
}
xhr.open('GET', 'http://whatever.com/wherever');
xhr.send();
Alternatively, write a little png parser in js (or compile libpng to javascript using something like emscripten), and do basically the same thing as above.
It probably wouldn't be too hard to write actually; since you don't care about the image data, you'd just have to write the chunk-traversing code. Read up on how chunks are laid out here, and figure out what chunk type you're storing the metadata in. Still, don't really recommend this if you can just use headers...

Getting started with calling APIs via XMLHttpRequest

I've just started to learn how to use APIs, but I'm having a little bit of trouble understanding exactly how to utilize them.
I was able to write the following code thanks to some online documentation, but I have some questions about how to add to it:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml", false); xhr.send();
console.log(xhr);
Now, when I run this code in my browser and I open the console, I get a dropdown with a whole bunch of stuff under it. First of all, how can I get the code to display JUST the response? I want the console to display just the XML to show when I run my code. Second of all, how do I parse the XML? Is there any way to get a value from an XML element and assign it to a JavaScript variable?
Thanks!
What you are printing is the XMLHttpRequest object itself, while what you actually want is the response from the request you've made. To get the response, you use
xhr.responseXML;
Which is a object of the type document. (See the MDN docs).
To exhibit the code, you can just
console.log(xhr.responseXML);
But to actually work with the response, you'll probably want to do as Josh suggested, and request from the API a JSON-formatted response (instead of a XML-formatted one).
You will probably want to do that asyncronously, too (see this). The page has a more robust example. Let's adapt it to show London's temperature:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log("Temperature(K): " + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
Being async means that the xhr.onLoad function will be executed as soon as the response is received. Thus all of your code will be executed sequentially, and only when the response is received the onLoad will be executed.
You can get the response as a Document object.
Using your code above, you can reference xhr.responseXML and use the Document documentation to learn how to grab what data you need.
That dropdown is probably your browser formatting the response object in an interactive way for you.
xmlDoc=xhr.responseXML; will give you the actual resulting text
Alternatively: you could request a JSON object to make working with the data much easier.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", false); xhr.send();
var data= JSON.parse(xhr.responseText); //data is now a javascript object full of the API data
Note how the url now reads mode=json now.

Parse json from an external site with JavaScript

I am trying to parse some json on an external site but I am having trouble. It must be with JavaScript or JQuery, as it is for a chrome extension. To get to the point:
I need to get the number from an external URL with the json {"_visitor_alertsUnread":"0"} and set the number returned to a variable. How do I go about doing this?
I have tried several things such as JSON.parse but it isn't working:(
In short: How do I get the number from this json, which is on an external site, and set it to a variable?
You cannot get data from an external URL (in a different domain) in Javascript unless the site supports JSONP or Cross-Origin Resource Sharing. If it does, then use XMLHttpRequest to get the data and JSON.parse() to read it.
Script:
var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'example.com/json', true );
xhr.onload = function () {
var unread = window.JSON.parse( xhr.responseText )._visitor_alertsUnread;
};
xhr.onerror = function () {
//process error
};
xhr.send();
Try this with http://api.jquery.com/jQuery.getJSON/
$.getJSON('your_url', function (jsonobj) {
var unread;
unread = jsonobj._visitor_alertsUnread;
});

Javascript on Firefox: Accessing binary data from html object possible?

On an html page I have an <object> that hosts a pdf.
I would need to access the binary data of the pdf via Javascript, but I cannot figure out how
to accomplish that. I get access to the object element itself but cannot think of a method for getting the data in it.
Is it possible at all?
You can not get the binary from an object tag, but you can make an AJAX request to the server and get it as ArrayBuffer by using the new responseType attribute:
var http = new XMLHttpRequest();
http.open("get", "somefile.pdf", true);
http.responseType = "arraybuffer";
http.onload = function(e)
{
if(http.response)
{
// http.response contains the file
}
};
http.send(null);
Note that this method only works in newer browsers and is obviously restricted by the Same-Origin-Policy.

Categories

Resources