Tat*_*vik 3 reactjs graphql axios
我对GraphQL有问题。我想将axios.post请求发送到我的服务器。我可以用邮递员来做:
{
"query":"mutation{updateUserCity(userID: 2, city:\"test\"){id name age city knowledge{language frameworks}}} "
}
Run Code Online (Sandbox Code Playgroud)
在graphiql中:
mutation {
updateUserCity(userID: 2, city: "test") {
id
name
age
city
knowledge {
language
frameworks
}
}
}
Run Code Online (Sandbox Code Playgroud)
但无法在我的代码中执行:(((这是我的代码段:
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'
}
})
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题?
我喜欢使用以下语法,它类似于接受的答案,但更明确。
请注意,variables对象嵌套在对象内部data,并且是对象的兄弟query。
const data = await axios({
url: API_URL,
method: 'post',
headers: {
'Content-Type': 'application/json',
// any other headers you require go here
},
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'
}
}
});
Run Code Online (Sandbox Code Playgroud)
query要在请求中传递的参数的值必须为字符串,并且传递给GraphQL查询的变量名称应以前缀$。您已在请求中将字符串文字用于变量。同样,可以在请求后使用variableskey 传递变量。
将您的代码更改为如下所示应该可以使其正常工作:
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'
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5492 次 |
| 最近记录: |