简体   繁体   English

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

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

I'm a new developer.我是新开发人员。 If you login to our website, JWT will be created.如果您登录我们的网站,将创建 JWT。 When I press the button, I have to put it in the API as a backend.当我按下按钮时,我必须把它放在 API 作为后端。 And if the screen is successful, the address in the API must be printed out.并且如果屏幕成功,则必须打印出API中的地址。 If it fails, 'authentication failure' should be displayed on the screen.如果失败,屏幕上应显示“身份验证失败”。 I want to do this.我想做这个。 Please help me.请帮我。

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;

Generally for any network operation, it's helpful to know when it's in progress, has finished, and/or has an error.通常,对于任何网络操作,了解它何时进行、何时完成和/或出现错误是有帮助的。 Let's set this up:让我们设置一下:

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);

During your POST, set the state variables accordingly:在 POST 期间,相应地设置 state 变量:

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

Now in your component return, you can conditionally render your different states, eg:现在在您的组件返回中,您可以有条件地呈现您的不同状态,例如:

// 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>}
  </>
)

Alternatively, you could leverage the variables slightly differently:或者,您可以稍微不同地利用变量:

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>
  </>
)

The ternary style can be a bit messy though.三元样式可能有点混乱。

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

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