簡體   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