Post mutation to graphql with axios

后端 未结 2 569
忘了有多久
忘了有多久 2020-12-29 10:16

This query in grahiql works:

mutation {
  addSkill(id:\"5\",name:\"Javascript\",level:1,type:\"frontend\") {
    status
    id
    name
    leve         


        
相关标签:
2条回答
  • 2020-12-29 10:42

    I would avoid including variables directly in the query like this, because that way you have to constantly adjust how your variables fit into the template literal, like stringifying stuff and adding quotes.

    Use graphql print to do it for you!

    Try this:

    import axios from 'axios';
    import { print } from 'graphql';
    import gql from 'graphql-tag';
    
    const ADD_SKILL = gql`
    mutation addSkill($id:String!, $name:String!, $level:Float!, $type:String!) {
      addSkill(id:$id, name:$name, level:$level, type:$type) { 
        status
        id
        name
        level
        type
      }
    }
    `
    
    axios
    .post(config.apiendpoint, {
      query: print(ADD_SKILL),
      variables: {
        id: String(id),
        name: this.form.name,
        level: parseFloat(this.form.level),
        type: this.form.type,
      },
    })
    .then(res => console.log(res))
    .catch(err => console.log(err))
    
    0 讨论(0)
  • 2020-12-29 10:43

    Found the problem.

    1. Remove the extra mutation
    2. Rmove the extra " after $name

    Update - a cleaner version:

    axios
    .post(config.apiendpoint, {
      query: `mutation {
          addSkill(id:"${id}", name:"${this.form.name}", level:${parseFloat(this.form.level)}, type:"${this.form.type}") {
            status
            id
            name
            level
            type
          }
        }
      `,
    }).then().catch()
    

    Here's the working request for reference.

    axios
    .post(config.apiendpoint, {
      query: `
        mutation addSkill($id:String!, $name:String!, $level:Float!, $type:String!) {
          addSkill(id:$id, name:$name, level:$level, type:$type) { 
            status
            id
            name
            level
            type
          }
        }
      `,
      variables: {
        id: String(id),
        name: this.form.name,
        level: parseFloat(this.form.level),
        type: this.form.type,
      },
    })
    .then(res => console.log(res))
    .catch(err => console.log(err))
    
    0 讨论(0)
提交回复
热议问题