使用 axios 请求 graphql 查询

Request a graphql query with axios

我正在尝试使用 axios 通过 graphql 查询发出请求但失败了。 这是我的查询

query {
  workspace(workspaceName: "Whosebug") {
    name
    company {
      name
    } 
  }
}

和我的代码块

  axios({
        url: "https://testurl.com/graphql",
        method: 'post', 
        query: ` query($workspaceName: String!)
           {
              workspace(workspaceName: $workspaceName) {
                 name
                 company {
                   name
                 } 
               }
           }
           `,
        variables: {
           workspaceName: CookieHelper.workspaceName,
        },
        forceResolve: resolve,
     })
        .then(res => {
           resolve(res);
        })
        .catch(err => {
           reject(err);
        });

我这样设置是因为 workspaceName 值将按参数工作。

Axios 在选项对象中没有 query 属性。您尝试发送到服务器的所有数据都应分配给 data 属性。或者使用 axios.post 函数,其中第二个参数与 axios() 上的 data 相同。

const query = `
query($workspaceName: String!) {
  workspace(workspaceName: $workspaceName) {
    name
    company {
      name
    } 
  }
}`;

const variables = {
  workspaceName: CookieHelper.workspaceName,
};

// Use `data` or..
axios({
  url: "https://testurl.com/graphql",
  data: {
    query,
    variables
  }
}).then(res => {
  resolve(res);
}).catch(err => {
  reject(err);
});

// ..use post where the second parameter is the same as data.
axios.post("https://testurl.com/graphql", {
  query,
  variables
}).then(res => {
  resolve(res);
}).catch(err => {
  reject(err);
});

我不确定 forceResolve: resolve 做了什么,所以我在示例中省略了它。