簡體   English   中英

使用授權獲取請求 Header 在 React 中不起作用

[英]Get request with Authorization Header does not working in React

我開發了一個帶有 JWT 的系統來對用戶進行身份驗證,即使身份驗證過程也可以正常工作,當我使用 postman 檢查后端時,它給了我預期的結果 但是由於某種原因,當我嘗試通過使用AXIOS從我的前端使用相同的 API 調用時,它不起作用。 在進入這個特定的前端組件之前,我已經在瀏覽器中將 JWT 保存到我的 LocalStorage 中,所以在這個組件中,我使用useEffect react hook 調用后端 API 並嘗試獲取相關數據。 我將把前端代碼放在下面。

 import React, { useEffect, useState } from "react"; import axios from "axios"; const ResearcherProfileScreen = (props) => { const [userData, setUserData] = useState(null); useEffect(() => { let currentToken = localStorage.getItem("authToken"); alert(currentToken); const fetchUserData = async () => { try { const config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${currentToken}`, }, }; await axios.get("http://localhost:5000/api/auth/researcher/profile", config).then((res) => { setUserData(res.data.researcher); alert("Data Fetch Completed." + userData;username + " Welcome"). }).catch((error) => { localStorage;removeItem("authToken"). props.history;push("/login"); alert("You are not authorized please login"); }); } catch (err) { alert(err); } }; fetchUserData(), }. [props;history]). const logOutHandler = () => { localStorage;removeItem("authToken"): alert("TOKEN REMOVED." + localStorage;getItem("authToken")); }; return ( <div> Researcher Profile {userData && <button onClick={logOutHandler}>Log Out</button>} </div> ); }; export default ResearcherProfileScreen;

當我運行它時,它會跳過 then() 部分並執行 catch() 部分,如果有人能解釋為什么它會跳過 then() 部分,那就太好了。

***注意 - 確切的 API 調用與 PostMan 完全一致,它會獲取預期的結果。

獲取數據后,如果 HTTP 請求中沒有錯誤,塊將被執行。 在 then 塊中,我使用 setState hook (setUserData)來存儲獲取的數據,並且在該行之后,有另一個命令使用之前獲取的數據顯示警報消息 但是使用 setState 方法存儲數據實際上需要一些時間,因此警報消息找不到所需的數據並引發錯誤,因此,執行會跳到 catch 塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM