【问题标题】:GraphQL Authentication with React TypeScript使用 React TypeScript 进行 GraphQL 身份验证
【发布时间】:2020-06-06 08:27:02
【问题描述】:

我有一个登录页面,当用户单击提交按钮时,我想从 GraphQL API 中可用的数据检查用户的身份验证。我尝试按照本教程进行操作:

https://www.apollographql.com/docs/react/networking/authentication/

在我的 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>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs typescript graphql apollo


    【解决方案1】:

    您需要先创建一个突变!这将为您提供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>
      );
    };
    
    

    注意我们如何将addTodo({ variables: { type: input.value } }); 变量传递到这里,您应该发送用户名和密码,而不是type。

    你可以这样做;

    login({variables: {username: this.state.username, password: this.state.password}})
    

    【讨论】:

    • 嘿,你能在这个沙盒上检查我的代码吗? codesandbox.io/s/…
    • 这还不是一个有效的例子。目前,每次单击登录按钮时,我的页面都会提醒“已提交”。即使输入的密码/用户名是错误的。我需要将从突变中接收到的令牌存储在 localstorage 中,但我不知道在哪里/如何这样做
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2021-05-09
    • 2021-05-10
    • 2018-08-18
    • 2020-09-26
    • 2018-02-08
    相关资源
    最近更新 更多