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

问题描述 投票:0回答:1

我通过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

语法有什么问题吗?

javascript xmlhttprequest graphql axios
1个回答
2
投票

根据文件:

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这样的客户端。

© www.soinside.com 2019 - 2024. All rights reserved.