pneuma
pneuma

Reputation: 319

Request a graphql query with axios

I'm trying to make a request with a graphql query using axios but failed. this is my query

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

and my code block

  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);
        });

I set it like this because workspaceName value will work parametrically.

Upvotes: 1

Views: 5433

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20954

Axios does not have a query property in the options object. All data you're trying to send to the server should be assigned to the data property. Or use the axios.post function where the second parameter is the same as data on axios().

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);
});

I'm not sure what forceResolve: resolve did, so I omitted it from the example.

Upvotes: 4

Related Questions