How I can get response from graphql server using pure js without libraries?
For example how I can do that using XMLHttpRequest
?
Query and serverUrl are below:
const serverUrl = '/'
const query = {
query: `{
viewer {
date
}
}`
};
How I can get response from graphql server using pure js without libraries?
For example how I can do that using XMLHttpRequest
?
Query and serverUrl are below:
const serverUrl = 'http://example./graphql/'
const query = {
query: `{
viewer {
date
}
}`
};
Share
Improve this question
asked Aug 30, 2019 at 5:52
Arseniy-IIArseniy-II
9,2555 gold badges27 silver badges51 bronze badges
1 Answer
Reset to default 8Use POST
request with 'Content-Type', 'application/json'
const yourServerUrl = 'http://example./graphql'
const yourQuery = {
query: `{
users {
firstName
}
}`
};
// below ordinary XHR request with console.log
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('POST', yourServerUrl);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
console.log('data returned:', xhr.response);
};
xhr.send(JSON.stringify(yourQuery));
source