繁体   English   中英

如何在“react”中将“token”发送到“Api”

[英]How to send "token" to "Api" in "react"

我是新开发人员。 如果您登录我们的网站,将创建 JWT。 当我按下按钮时,我必须把它放在 API 作为后端。 并且如果屏幕成功,则必须打印出API中的地址。 如果失败,屏幕上应显示“身份验证失败”。 我想做这个。 请帮我。

import axios from 'axios';
import React, { useState } from 'react';
import { Button } from '@material-ui/core';

function TestPage() {
  const onLogin = () => {
    var variables = {
      email: email,
      password: password,
    };

    Axios.post('/auth/login', variables).then((res) => {
      setCookie('token', res.payload.accessToken);
      setCookie('exp', res.payload.accessTokenExpiresIn);
      Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
      Axios.get('/user/me').then((res) => {
        console.log(res);
      });
    });
  };

  return (
    <>
      <div>
        <Button
          variant="contained"
          color="primary"
          style={{ width: '200px' }}
          onClick={(e) => customFetch(e)}>
          address
        </Button>
      </div>
      {address && <div>{address}</div>}
    </>
  );
}

export default TestPage;

通常,对于任何网络操作,了解它何时进行、何时完成和/或出现错误是有帮助的。 让我们设置一下:

const [isLoading, setIsLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)

// inside your `onLogin` function...
setIsLoading(true);
Axios.post('/auth/login', variables).then((res) => {
  setCookie('token', res.payload.accessToken);
  setCookie('exp', res.payload.accessTokenExpiresIn);
  Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
  // bit messy using the same error state for both but you can always refactor
  Axios.get('/user/me').then((res) => {
        console.log(res);
        setData(res); // not sure where the actual data is with Axios
  }).catch(err => setError(err);
}).catch(err => setError(err));
setIsLoading(false);

在 POST 期间,相应地设置 state 变量:

  1. 发帖前, setIsLoading(true)
  2. 成功后, setData(response.data) // whatever your payload might be
  3. 在错误/失败时, setError(error)

现在在您的组件返回中,您可以有条件地呈现您的不同状态,例如:

// your component body
if (isLoading) return (
  // a loading state
)
if (error) return (
  // an error state
  // e.g. "Authentication Failure"
)
return (
  // your success/ideal state
  // e.g:
  <>
    <div>
      <Button
        variant="contained"
        color="primary"
        style={{ width: '200px' }}
        onClick={(e) => customFetch(e)}>
        address
      </Button>
    </div>
    {address && <div>{address}</div>}
  </>
)

或者,您可以稍微不同地利用变量:

return (
  <>
    <div>
      <Button
        variant="contained"
        color="primary"
        style={{ width: '200px' }}
        onClick={(e) => customFetch(e)}
        disabled={isLoading}>
        address
      </Button>
    </div>
    <div>
      {isLoading
        ? 'Checking...'
        : error !== null
        ? 'Something went wrong'
        : 'Ready to submit'}
    </div>
  </>
)

三元样式可能有点混乱。

暂无
暂无

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

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