GraphQl客户端查询/突变不起作用(Vanilla JS)

时间:2020-09-07 23:03:29

标签: javascript graphql apollo-client

所以我昨天才刚开始使用GraphQl,我对如何从客户端传递查询感到有些困惑。

我想要的:

我只想使用简单的fetch进行查询/突变:

const mutation = `
  // even better would be: UserRegister( firstName: ${firsName}, lastName: ${lastName}, email: ${email}, password: ${password} )
  UserRegister( firstName: "John", lastName: "Doe", email: "john_doe@outlook.com", password: "123" ) {
    _id,
    firstName,
    lastName,
    email
  }
`

const options = {
  'method': 'POST',
  'headers': { 'Content-Type': 'application/json' },
  'body': JSON.stringify( { mutation } )
}

const res = await fetch( 'http://localhost:3000/graphql', options )

现在,当从客户端运行此命令时,出现http://localhost:3000/graphql 400 (Bad Request)错误。

但是当我在操场上运行相同的查询时,它就可以正常工作:

enter image description here

我在这里做什么错了?


有效查询(无法回答我的问题):

我设法使查询与Apollo客户端一起使用,但是我感觉这是很多查询代码。使用Apollo客户端时,是否可以用较少的代码编写查询?当服务器上的架构中已经定义了变量类型时,为什么我需要在这里定义变量类型(服务器不能执行验证)?

const client = new ApolloClient( {
  'uri': 'http://localhost:3000/graphql',
  'cache': new InMemoryCache()
} )

const mutation = gql`
  // why this?
  mutation UserRegister( $firstName: String!, $lastName: String!, $email: String!, $password: String! ) {
    UserRegister( firstName: $firstName, lastName: $lastName, email: $email, password: $password ) {
      _id,
      firstName,
      lastName,
      email
    }
  }
`

const res = await client.mutate( {
  mutation,
  // also why defining the variables here?
  'variables': {
    'firstName': 'John',
    'lastName': 'Doe',
    'email': 'john_doe@outlook.com',
    'password': '123'
  }
} )

1 个答案:

答案 0 :(得分:0)

@xadm向我指出了解决方案:

const query = `
  mutation {
    UserRegister( firstName: "John", lastName: "Doe", email: "john_doe@outlook.com", password: "123" ) {
      _id,
      firstName,
      lastName,
      email
    }
  }
`

const options = {
  'method': 'POST',
  'headers': { 'Content-Type': 'application/json' },
  'body': JSON.stringify( { query } )
}

const res = await fetch( 'http://localhost:3000/graphql', options )