Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用React-TypeScript的GraphQL身份验证_Javascript_Reactjs_Typescript_Graphql_Apollo - Fatal编程技术网

Javascript 使用React-TypeScript的GraphQL身份验证

Javascript 使用React-TypeScript的GraphQL身份验证,javascript,reactjs,typescript,graphql,apollo,Javascript,Reactjs,Typescript,Graphql,Apollo,我有一个登录页面,当用户单击Submit按钮时,我想从GraphQLAPI中可用的数据检查用户的身份验证。我尝试遵循本教程: 在我的graphQL操场上,我使用了这个变异,然后一个令牌返回给我 mutation{ loginEmail(email: "${this.state.email}", password: "${this.state.password}") }`, 然而,我只能想办法将它集成到我的代码中。我应该在

我有一个登录页面,当用户单击Submit按钮时,我想从GraphQLAPI中可用的数据检查用户的身份验证。我尝试遵循本教程:

在我的graphQL操场上,我使用了这个变异,然后一个令牌返回给我

mutation{
             loginEmail(email: "${this.state.email}",
             password: "${this.state.password}")
          }`,
然而,我只能想办法将它集成到我的代码中。我应该在哪里输入用户名和密码?如果我在按钮上调用_AuthLink,就会出现重载错误

以下是我登录页面的代码:

export default class LoginPage extends Component <{}, { email: string,password: string, loggedIn: boolean}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      email: '',
      password: '',
      loggedIn: false,
    };
  }

  _httpLink = createHttpLink({
    uri: 'https:myapilink/graphql',
  });

  _AuthLink = setContext((_, { headers }) => {
    // get the authentication token from local storage if it exists
    const token = localStorage.getItem('token');
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
      }
    }
  });

  _client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  });

  render() {
    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div style={{
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center'}}>
          <Avatar>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form style={{width: '100%'}} noValidate>
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              onChange={e => {
                this.setState({email: e.target.value})
              }}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              onChange={e => {
                this.setState({password: e.target.value})
            }}
            />
            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            />
            <br></br>
            <Button className='button-center'
            //onClick={this._AuthLink}
            >
            Submit</Button>
            <br></br>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2">
                  Forgot password?
                </Link>
              </Grid>
              <Grid item>
                <Link href="#" variant="body2">
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
        <Box mt={8}>
          <Copyright />
        </Box>
      </Container>
    );
  }
}
导出默认类LoginPage扩展组件{
构造函数(道具:只读){
超级(道具);
此.state={
电子邮件:“”,
密码:“”,
洛格丁:错,
};
}
_httpLink=createHttpLink({
uri:'https:myapilink/graphql',
});
_AuthLink=setContext(({headers})=>{
//从本地存储中获取身份验证令牌(如果存在)
const token=localStorage.getItem('token');
//将标题返回到上下文,以便httpLink可以读取它们
返回{
标题:{
…标题,
授权:令牌?`Bearer${token}`:“”,
}
}
});
_客户端=新客户端({
链接:authLink.concat(httpLink),
缓存:新的InMemoryCache()
});
render(){
返回(
登录
{
this.setState({email:e.target.value})
}}
/>
{
this.setState({密码:e.target.value})
}}
/>


提交

忘记密码了? {“没有帐户?注册”} ); } }
您需要先创建一个突变!这将为您提供
mutate
函数,您可以传递变量等等。看看这个例子

const AddTodo = () => {
  let input;

  return (
    <Mutation mutation={ADD_TODO}>
      {(addTodo, { data }) => (
        <div>
          <form
            onSubmit={e => {
              e.preventDefault();
              addTodo({ variables: { type: input.value } });
              input.value = '';
            }}
          >
            <input
              ref={node => {
                input = node;
              }}
            />
            <button type="submit">Add Todo</button>
          </form>
        </div>
      )}
    </Mutation>
  );
};


嘿,你能检查一下我在这个沙箱上的代码吗?这还不是一个有效的例子。目前,每次单击登录按钮时,我的页面都会提示“已提交”。即使输入的密码/用户名错误。我需要在localstorage中存储应从突变中接收的令牌,但我不知道在何处/如何执行此操作
login({variables: {username: this.state.username, password: this.state.password}})