如何使用XMLHttpRequest从GraphQL服务器获取数据?

3

如何在不使用库的情况下使用纯JS从graphql服务器获取响应?

例如,我如何使用XMLHttpRequest来实现这一点? 以下是查询和serverUrl:

const serverUrl = 'http://example.com/graphql/'
const query = {
    query: `{
        viewer {
            date
        }
    }`
};
1个回答

8

使用 POST 请求,并设置请求头 '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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接