繁体   English   中英

将XHR请求转换为axios以从GraphQL服务器请求数据

[英]Converting XHR request to axios to request data from GraphQL server

我正在通过XHR从GraphQLHub请求数据:

const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author {  username commentKarma } } } } } }';

const xhr = new XMLHttpRequest(); 
xhr.open("get", 'https://www.graphqlhub.com/graphql?query=' + encodeURIComponent(query), true);
xhr.responseType = "json";
xhr.onload = () => console.log(xhr.response);
xhr.send();

这可行。 但是我尝试将其转换为axios,如下所示:

const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author {  username commentKarma } } } } } }';

axios({
    url: "https://www.graphqlhub.com/graphql",
    method: "get",
    data: {
        query: encodeURIComponent(query)
    }
}).then((result) => {
    console.log(result.data);
});

但我收到此错误:

Uncaught (in promise) Error: Request failed with status code 400

语法有问题吗?

根据文档:

data是要作为请求正文发送的数据。 仅适用于请求方法“ PUT”,“ POST”和“ PATCH”。

由于您的请求方法是GET ,因此数据将被忽略。 您应该改用params 我们也不需要编码我们的参数,因为axios已经为我们做到了。

axios({
  url: "https://www.graphqlhub.com/graphql",
  method: "get",
  params: {
    query,
  }
})

不过,最好改用POST,因为某些服务器不允许将变异作为GET请求发送。

axios({
  url: "https://www.graphqlhub.com/graphql",
  method: "get",
  data: {
    query,
  }
})

或者,更好的是,仅使用Apollo之类的客户端。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM