gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:13:30 26 4
gpt4 key购买 nike

我通过 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 is the data to be sent as the request body. Only applicable for request methods 'PUT', 'POST', and '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 的客户端即可.

关于javascript - 将XHR请求转换为axios以从GraphQL服务器请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com