Tatevik
Tatevik

Reputation: 385

GraphQL post request in axios

I have a problem with GraphQL. I want to send axios.post request to my server. I can do it in postman:

{
    "query":"mutation{updateUserCity(userID: 2, city:\"test\"){id name age city knowledge{language frameworks}}} "
}

and in graphiql:

mutation {
  updateUserCity(userID: 2, city: "test") {
    id
    name
    age
    city
    knowledge {
      language
      frameworks
    }
  }
}

but can't do it in my code:(( here is my code snippet:

const data = await axios.post(API_URL, {
  query: mutation updateUserCity(${ id }: Int!, ${ city }: String!) {
    updateUserCity(userID: ${ id }, city: ${ city }){
      id
      name
      age
      city
      knowledge{
        language
        frameworks
      }
    }
  }
}, {
    headers: {
      'Content-Type': 'application/json'
    }
  })

what's wrong in my code?

Upvotes: 25

Views: 62605

Answers (6)

M.P.D.K. WEERAKOON
M.P.D.K. WEERAKOON

Reputation: 1

Pass data like this:

const email = "[email protected]";
const password = "123";

const data = await axios.post(
  API_URL.Loging,
  {
    query: `query{
      login(
        email:"${email}", 
        password:"${password}"
      )
      {
        userId
        token
      }
    }`,
  }
);
    

Upvotes: 0

NWRichmond
NWRichmond

Reputation: 323

I enjoy using the following syntax, which is similar to the accepted answer, but more explicit.

Note that the variables object is nested inside of the data object, and is a sibling of the query object.

const data = await axios({
  url: API_URL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
    // ...other headers
  },
  data: {
    query: `
      mutation updateUserCity($id: Int!, $city: String!) {
        updateUserCity(userID: $id, city: $city) {
          id
          name
          age
          city
          knowledge {
            language
            frameworks
          }
        }
      }
    `,
    variables: {
      id: 2,
      city: 'Test'
    }
  }
});

Upvotes: 12

atazmin
atazmin

Reputation: 5697

for WordPress GQL https://docs.wpgraphql.com/getting-started/posts/ This seem to work for me at this moment with Nuxt

async asyncData() {
const data = {
  query: `query GET_POSTS($first: Int) {
    posts(first: $first) {
      edges {
        node {
          postId
          title
          excerpt
          date
          content
          author {
            node {
              username
            }
          }
        }
      }
    }
  }`,
  variables: {
    first: 5
  }
}

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  data: data,
  url: 'http://localhost/graphql'
};
    
try {
  const response = await axios(options);

  console.log(response.data.data.posts.edges);
  console.log(response.data.data.posts.edges.length);
} catch (error) {
  console.error(error);
}

},

Upvotes: 1

Rolly
Rolly

Reputation: 3375

i would like to share you my simple working example

            let id = "5c9beed4a34c1303f3371a39";
            let body =  { 
                query: `
                    query {
                        game(id:"${id}") {
                            _id
                            title
                        }
                    }
                `, 
                variables: {}
            }
            let options = {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            axios.post('http://localhost:3938/api/v1/graphql',body, options)
                .then((response)=>{
                    console.log(response);
                });

Upvotes: 2

Raeesaa
Raeesaa

Reputation: 3316

Value of query parameter to be passed in request has to be string and names of variables passed to GraphQL queries should be prefixed by $. You have used string literals for variables in request instead. Also, variables can be passed in post request using variables key.

Changing your code to something like below should get it to working:

const data = await axios.post(API_URL, {
  query: `mutation updateUserCity($id: Int!, $city: String!) {
    updateUserCity(userID: $id, city: $city){
      id
      name
      age
      city
      knowledge{
        language
        frameworks
      }
    }
  }`,
  variables: {
    id: 2,
    city: 'Test'
  }
}, {
    headers: {
      'Content-Type': 'application/json'
    }
  })

Upvotes: 61

Samuel Imolorhe
Samuel Imolorhe

Reputation: 724

It seems you're trying to pass variables into the query. Unless I'm wrong, what you have in the axios call and the others are different.

const data = await axios.post(API_URL, {
  query: `
    updateUserCity(userID: ${id}, city:${city}){
      id
      name
      age
      city
      knowledge{
        language
        frameworks
      }
    }
  `
}, {
  headers: {
    'Content-Type': 'application/json'
  }
});

I believe this should work, assuming you have the variables id and city defined before this call.

Upvotes: 0

Related Questions