GraphQL post request in axios
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'
}
})
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);
});
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'
}
}
});