代码之家  ›  专栏  ›  技术社区  ›  catandmouse

将xhr请求转换为axios以从graphql服务器请求数据

  •  0
  • catandmouse  · 技术社区  · 6 年前

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

    语法有什么问题吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Daniel Rearden    6 年前

    根据文件:

    data 是要作为请求主体发送的数据。仅适用于请求方法“put”、“post”和“patch”。

    因为你的请求方法是 GET ,数据将被忽略。你应该用 params 相反。我们也不需要编码我们的参数,因为axios已经为我们做了这些。

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

    不过,最好使用post,因为有些服务器不允许将突变作为 得到 请求。

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

    或者,更好的办法是,像 Apollo