AXIO中的GraphQL发布请求 [英] GraphQL post request in axios

查看:172
本文介绍了AXIO中的GraphQL发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对GraphQL有问题.我想将axios.post请求发送到我的服务器.我可以用邮递员来做:

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}}} "
}

和在graphiql中:

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'
    }
  })

我的代码有什么问题?

推荐答案

要在请求中传递的query参数的值必须为字符串,并且传递给GraphQL查询的变量名称应以$为前缀.您已在请求中将字符串文字用于变量.同样,可以使用variables键在发布请求中传递变量.

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'
    }
  })

这篇关于AXIO中的GraphQL发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆