我在使用 GraphQL 时遇到问题。我想向我的服务器发送 axios.post 请求。我可以在 postman 中做到这一点:
{
"query":"mutation{updateUserCity(userID: 2, city:\"test\"){id name age city knowledge{language frameworks}}} "
}
在 graphiql 中:
mutation {
updateUserCity(userID: 2, city: "test") {
id
name
age
city
knowledge {
language
frameworks
}
}
}
但在我的代码中无法做到这一点:((这是我的代码片段:
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'
}
})
我的代码有什么问题吗?
最佳答案
请求中传递的query
参数的值必须是字符串,并且传递给GraphQL查询的变量名称应以$
为前缀。您已在请求中使用字符串文字作为变量。此外,可以使用 variables
键在 post 请求中传递变量。
将代码更改为如下所示应该可以使其正常工作:
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'
}
})
关于reactjs - axios 中的 GraphQL post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52816623/