最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论