我对GraphQL有问题。我想将axios.post请求发送到我的服务器。我可以用邮递员来做:
{ "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查询的变量名称应以前缀$。您已在请求中将字符串文字用于变量。同样,可以在发布请求中使用variableskey 传递变量。
query
$
variables
将您的代码更改为如下所示应该可以使其正常工作:
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' } })