javascript - How to fetch from graphql server using XMLHttpRequest? - Stack Overflow

How I can get response from graphql server using pure js without libraries?For example how I can do tha

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
Add a ment  | 

1 Answer 1

Reset to default 8

Use 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745256796a4619006.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信