Post mutation to graphql with axios

ε祈祈猫儿з 提交于 2019-12-04 10:55:24

问题


This query in grahiql works:

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

What is the equivalent to post with axios?

I've tried this, but keep getting a 400 request response.

{"errors":[{"message":"Syntax Error: Unterminated string.","locations":[{"line":3,"column":82}]}]}

This is what I tried:

axios
  .post(config.apiendpoint, {
    query: `
      mutation addSkill($id:String!, $name:String!, $level:Float!, $type:String!) {
        mutation addSkill(id:$id, name:$name", level:$level, type:$type) { 
          status
          id
          name
          level
          type
        }
      }
    `,
    variables: {
      id: String(id),
      name: this.form.name,
      level: this.form.level,
      type: this.form.type,
    },
  })
  .then(res => console.log(res))
  .catch(err => console.log(err))

Am sure the values in the variables are of the right type and is not empty too.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/51630137/post-mutation-to-graphql-with-axios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!