You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Graphcool调用createUser Mutation出现语法错误求助

解决Graphcool createUser Mutation的语法错误问题

我一眼就瞅出你的问题出在GraphQL Mutation的语法和参数结构上,咱们一步步来修正:

错误原因分析

  1. 变量定义语法错误:你把变量$email和$password直接写在了authProvider的字段里,这不符合GraphQL的语法规范——变量必须在mutation的开头统一声明,之后再在字段中引用。
  2. Graphcool API结构理解偏差:Graphcool的createUser接口要求用户的认证信息嵌套在authProvider字段下,而不是直接把email、password作为顶层参数传递。

修正后的完整代码

先看核心的Mutation定义,再看完整组件代码:

const CREATE_USER = gql`
mutation CreateUser($email: String!, $password: String!) {
  createUser(
    authProvider: {
      email: {
        email: $email
        password: $password
      }
    }
  ) {
    id
    email
  }
}
`

这里几个关键调整:

  • 开头先声明变量$email: String!, $password: String!,!表示这两个字段是必填项,符合注册场景的需求。
  • 按照Graphcool的规范,把email和password放在authProvider.email的嵌套结构里传递。
  • 重要注意:移除了返回值中的password字段,这是敏感信息,绝对不要在查询中请求返回它!

然后是完整的组件代码:

// 确保导入了必要的依赖
import { gql, compose, graphql } from 'react-apollo';
import React from 'react';

class Register extends React.Component {
  state = {
    email: '',
    password: ''
  };

  // 处理输入变化的方法
  handleInputChange = (e) => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  handleSubmit = () => {
    this.props
      .createUser({ variables: { email: this.state.email, password: this.state.password } })
      .then(({ data }) => { alert(JSON.stringify(data)) })
      .catch(error => { alert('There is a problem ' + error) })
  };

  render() {
    return (
      <div>
        <input
          type="email"
          name="email"
          value={this.state.email}
          onChange={this.handleInputChange}
          placeholder="Email"
        />
        <input
          type="password"
          name="password"
          value={this.state.password}
          onChange={this.handleInputChange}
          placeholder="Password"
        />
        <button onClick={this.handleSubmit}>Register</button>
      </div>
    );
  }
}

const RegisterData = compose(graphql(CREATE_USER, { name: 'createUser' }))(Register);
export default RegisterData;

额外提示

  • 确保你的React组件已经正确设置了Apollo Client的上下文,不然请求还是会失败。
  • 如果还是有问题,可以检查Graphcool的控制台,确认你的数据模型中User类型确实配置了email/password的认证方式。

内容的提问来源于stack exchange,提问作者Harika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:32:13