如何在不使用库的情况下使用纯JS从graphql服务器获取响应?
例如,我如何使用XMLHttpRequest
来实现这一点?
以下是查询和serverUrl:
const serverUrl = 'http://example.com/graphql/'
const query = {
query: `{
viewer {
date
}
}`
};
例如,我如何使用XMLHttpRequest
来实现这一点?
以下是查询和serverUrl:
const serverUrl = 'http://example.com/graphql/'
const query = {
query: `{
viewer {
date
}
}`
};
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));