Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch from graphql server using XMLHttpRequest?

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.com/graphql/'
const query = {
    query: `{
        viewer {
            date
        }
    }`
};
like image 761
Arseniy-II Avatar asked Jun 25 '26 02:06

Arseniy-II


1 Answers

Use POST request with 'Content-Type', 'application/json'

const yourServerUrl = 'http://example.com/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

like image 74
Arseniy-II Avatar answered Jun 30 '26 19:06

Arseniy-II



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!