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

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

问题描述

我对 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 键在 post 请求中传递变量.

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

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

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