如何从Redux商店获得代币?

hpxqektj  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(148)

每次我想使用这个组件时,我都必须更改令牌。我该怎么做?我希望有人能理解我的意思。干杯,对不起,我的英语不好,我也是React的新手。我会很感激帮助

import React, {useEffect} from 'react'
import { Button } from "@chakra-ui/react";
import { MdAccountCircle  } from "react-icons/md"
import { toast } from 'react-toastify'

const AutoGenerateCustomers = () => {

    const showToastMessage = () => {
        toast.success('Customer generated!', {
            position: toast.POSITION.TOP_RIGHT
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
          const generate_customers = {};
          const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJpZCI6MywiZGF0ZSI6MTY3OTU5OTczNDkwNSwiaWF0IjoxNjc5NTk5NzM0LCJleHAiOjE2Nzk2Mjg1MzR9.uVAxYt7uZMZ1qBBCbkqnLkerFRszKpR68ULFCkxBhv4"
          e.preventDefault();
          fetch('http://localhost:8000/api/v1/customer/generate-customers', {
            method:'POST',
            headers: {
              "Authorization": `Bearer ${token}`,
              "Content-Type": "application/json"
            },
            body: JSON.stringify(generate_customers)
          }).then(() =>{
            console.log('Generated')
          })
        }
  return (
    <div>
      <Button
        onClick={(ev) => {
            handleSubmit(ev);
            showToastMessage();   
          }}
        variant='outline'
        bg='#f4f8fc' color='#002C8A'
        _hover={{ bg: "#f7f9gz" }}
        leftIcon={<MdAccountCircle size={23} />}
        width="200px"
        textColor="#002c8a"
        borderRadius="lg"
        fontSize="sm"
        fontWeight="normal"
      >
        Auto-Generate
      </Button>
    </div>
  );
}

export default AutoGenerateCustomers
55ooxyrt

55ooxyrt1#

假设您使用oAuth进行认证,您需要从oAuth提供者那里获取您的token。例如,这个Stack Overflow question中的接受答案有一个名为getToken的函数,该函数向 https://xxx123.caspio.com/oauth/token 发出POST请求,以接收新的token。然后,新的token将用于CallWebAPI函数中。
在本例中,您将在handleSubmit函数中使用新令牌。如果您有自己的getToken函数,则可以执行类似于以下示例的操作。在此示例中,该按钮处于禁用状态,直到从oAuth提供程序接收到新令牌并通过setToken分配给token常量。

import React, {useEffect} from 'react'
import { Button } from "@chakra-ui/react";
import { MdAccountCircle  } from "react-icons/md"
import { toast } from 'react-toastify'

const AutoGenerateCustomers = () => {
    const [ token, setToken ] = React.useState( null );

    useEffect( () => {
        if ( token == null ) {
            getToken().then( ( token ) => {
                setToken( token );
            } );
        }
    }, [ token ] );

    function getToken() {
        // Asynchronous call to an oAuth provider using a
        // client ID and a client secret, that returns
        // an object containing the token.

        ...

    }

    const showToastMessage = () => {
        toast.success('Customer generated!', {
            position: toast.POSITION.TOP_RIGHT
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const generate_customers = {};
        e.preventDefault();
        fetch('http://localhost:8000/api/v1/customer/generate-customers', {
            method:'POST',
            headers: {
                "Authorization": `Bearer ${token}`,
                "Content-Type": "application/json"
            },
            body: JSON.stringify(generate_customers)
        }).then(() =>{
            setToken( null );
            console.log('Generated')
        })
    }

    return (
         <div>
            <Button
                disabled={ token == null }
                onClick={(ev) => {
                    handleSubmit(ev);
                    showToastMessage();
                }}
                variant='outline'
                bg='#f4f8fc' color='#002C8A'
                _hover={{ bg: "#f7f9gz" }}
                leftIcon={<MdAccountCircle size={23} />}
                width="200px"
                textColor="#002c8a"
                borderRadius="lg"
                fontSize="sm"
                fontWeight="normal"
            >
                Auto-Generate
            </Button>
        </div>
    );
}

export default AutoGenerateCustomers

相关问题