使用axios将突变发布到graphql

res*_*ing 8 graphql axios

此查询grahiql有效:

mutation {
  addSkill(id:"5",name:"Javascript",level:1,type:"frontend") {
    status
    id
    name
    level
    type
  }
}
Run Code Online (Sandbox Code Playgroud)

用post相当于什么axios

我已经尝试过了,但是一直收到400请求响应。

{“ errors”:[{“ message”:“语法错误:未终止的字符串。”,“ locations”:[{“ line”:3,“ column”:82}]}]}}

这是我尝试的:

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))
Run Code Online (Sandbox Code Playgroud)

确保中的值variables正确type,并且也不为空。

res*_*ing 9

发现问题了。

  1. 去除多余的 mutation
  2. Rmove the extra "after$name

更新 - 一个更干净的版本

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()
Run Code Online (Sandbox Code Playgroud)

这是工作请求以供参考。

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))
Run Code Online (Sandbox Code Playgroud)


Mat*_*ira 8

我会避免像这样直接在查询中包含变量,因为那样一来,您就必须不断调整变量如何适合模板文字,例如对内容进行字符串化和添加引号。

graphql print它来为你做!

尝试这个:

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))
Run Code Online (Sandbox Code Playgroud)