首页 > 解决方案 > axios 中的 GraphQL 发布请求

问题描述

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

我的代码有什么问题?

标签: reactjsgraphqlaxios

解决方案


要在请求中传递的参数值query必须是字符串,并且传递给 GraphQL 查询的变量名称应以$. 您已将字符串文字用于请求中的变量。此外,可以使用variableskey 在 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'
    }
  })

推荐阅读