使用 axios 将变异发布到 graphql [英] Post mutation to graphql with axios

查看:33
本文介绍了使用 axios 将变异发布到 graphql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

grahiql 中的这个查询有效:

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

axios 发布帖子的等价物是什么?

What is the equivalent to post with axios?

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

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

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

{"errors":[{"message":"Syntax Error: Unterminated string.","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))

我确信 variables 中的值是正确的 type 并且也不为空.

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

推荐答案

我会避免像这样直接在查询中包含变量,因为那样你必须不断调整你的变量如何适应模板文字,比如字符串化的东西和添加引号.

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.

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

这篇关于使用 axios 将变异发布到 graphql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆