我整天都在为我的应用设置授权,一直在研究这个问题,并且意识到了此错误的问题
Cannot return null for non-nullable field Query.login
来自AuthPage.tsx
中这段代码的词干。
return res.json();
从GraphQL返回数据(返回200响应,这是很好的信息)之后,我不太确定处理数据的最佳方法。
这是名为authorisation
的完整AuthPage.tsx
组件
import React, { Component } from 'react';
import './AuthPage.scss';
export class AuthPage extends React.Component {
state = {
isLogin: true
}
constructor(props: any) {
super(props);
this.emailEl = React.createRef();
this.passwordEl = React.createRef();
}
emailEl: React.RefObject<any>;
passwordEl: React.RefObject<any>;
switchModeHandler = () => {
this.setState((prevState: any) => {
return {isLogin: !prevState.isLogin}
})
}
submitHandler = (event: any) => {
event.preventDefault();
const email = this.emailEl.current.value;
const password = this.passwordEl.current.value;
if (email.trim().length === 0 || password.trim().length === 0) {
return
}
let requestBody = {
query: `
query {
login(email: "${email}", password: "${password}") {
userId
token
tokenExpiration
}
}
`
};
if (!this.state.isLogin) {
requestBody = {
query: `
mutation {
createUser(id: "", email: "${email}", password: "${password}") {
id
email
password
}
}
`
}
}
fetch('http://localhost:4000/graphql', {
method: 'POST',
body: JSON.stringify(requestBody),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error('Failed!');
}
return res.json();
})
.then(resData => {
console.log(resData);
})
.catch(err => {
console.log(err);
});
};
render() {
return(
<form className="login" onSubmit={this.submitHandler}>
<div className="form-control">
<label className={"label"} htmlFor={"email"}>Email:</label>
<input type="email" placeholder={"Email address"} id={"email"} ref={this.emailEl}/>
</div>
<div className="form-control">
<label className={"label"} htmlFor={"password"}>Password:</label>
<input type="password" placeholder={"Enter password"} ref={this.passwordEl}/>
</div>
<button type={"submit"} className={"button"}>Login</button>
<button type={"button"} className={"button"} onClick={this.switchModeHandler}>Switch to {this.state.isLogin ? 'Signup' : 'Login'}</button>
</form>
)
}
}
export default AuthPage;
模式
module.exports = `
type User {
id: ID!
email: String!
password: String
}
type AuthData {
userId: ID!
token: String!
tokenExpiration: Int!
}
input UserInput {
email: String!
password: String!
}
type Query {
user(id: String!): User
users: [User]
login(email: String!, password: String!): AuthData!
}
type RootMutation {
createUser(userInput: UserInput): User
}
type Mutation {
createUser(id: String, email: String!, password: String!): User
editUser(id: String, email: String): User
deleteUser(id: String, email: String): User
}
`;
我的目标是从服务器返回GQL响应并将其正确格式化为响应,然后返回AuthData
但最重要的是摆脱这个错误
Cannot return null for non-nullable field Query.login
。