简体   繁体   English

GraphQl 客户端查询/变异不起作用(vanilla js)

[英]GraphQl client query/mutation not working ( vanilla js )

So I just started using GraphQl yesterday and I'm a little bit confused about how to pass my queries from the client.所以我昨天才开始使用 GraphQl,我对如何从客户端传递我的查询有点困惑。

What I want:我想要的是:

I just want to query/mutate with a simple fetch :我只想使用简单的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 )

Now when running this from the client I get an http://localhost:3000/graphql 400 (Bad Request) error.现在,当从客户端运行它时,我收到一个http://localhost:3000/graphql 400 (Bad Request)错误。

But when I run the same query with the playground it works just fine:但是当我在操场上运行相同的查询时,它工作得很好:

在此处输入图片说明

What am I doing wrong here?我在这里做错了什么?


Working query (not answer to my question):工作查询(不回答我的问题):

I managed to get my query working with Apollo client, but I have the feeling that this is a lot of code just for a query.我设法让我的查询与 Apollo 客户端一起工作,但我觉得这是很多只用于查询的代码。 When using Apollo client is there a way to write the query with less code?使用 Apollo 客户端时,有没有办法用更少的代码编写查询? Why do I need to define the variable types here when they're already defined in the schema on the server (couldn't the server do the validation)?为什么我需要在这里定义变量类型,因为它们已经在服务器的架构中定义了(服务器不能进行验证)?

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

@xadm pointed me to the solution: @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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM