【发布时间】:2020-12-26 07:49:29
【问题描述】:
所以我昨天才开始使用 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) 错误。
但是当我在操场上运行相同的查询时,它工作得很好:
我在这里做错了什么?
有效查询(不回答我的问题):
我设法让我的查询与 Apollo 客户端一起工作,但我觉得这只是一个查询的大量代码。使用 Apollo 客户端时,有没有办法用更少的代码编写查询?变量类型已经在服务器的schema中定义了,为什么还要在这里定义变量类型(服务器不能做验证)?
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'
}
} )
【问题讨论】:
-
'大量代码'?只是规格......以避免硬编码/字符串操作,更安全的通信,验证等......不值得吗?回去休息吗?
-
不一样的查询/突变...命名 const 'mutation' 不会使其成为突变
-
@xadm 感谢为我指出了解决方案,我认为我需要通过
{ mutation: ... }进行突变和{ query: ... }进行查询。
标签: javascript graphql apollo-client