Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - GraphQL post request in axios

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

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

what's wrong in my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...