๐๐ Basic GraphQL with Vue and XMLHttpRequest
2 min readFeb 28, 2018
Just make a XMLHttpRequest.
First, we need to create a Vue project using the vue-cli:
$ vue create basicql
We are going to use FakerQL to test our queries.
Here is an article I used to learn:
Now we run a sample query in the browser:
Lets check this locally on the command line with curl:
$ curl 'https://fakerql.com/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: */*' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://fakerql.com' --data-binary '{"query":"{\n products: allProducts(count: 25) {\n id\n name\n price\n }\n}","operationName":null}' --compressed
Open main.js, this is where the project gets bootstrapped:
Add the following to main.js:
let query = {
query: `{
products: allProducts(count: 25) {
id
name
price
}}`
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", "https://fakerql.com/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
console.log('data returned:', xhr.response);
}
xhr.send(JSON.stringify(query));
Open http://127.0.0.1: