[英]Not able to get data from AXIOS inside useEffect()
我試圖在 React 的useEffect()中從axios獲取數據。 我測試了后端它工作正常,但在前端我收到錯誤401(未經授權)
反應代碼:
import { useEffect, useState } from "react";
import axios from "axios";
function UpdateItem({ match, history }) {
const [title, setTitle] = useState();
const [description, setDescription] = useState();
...
useEffect(() => {
const fetching = async () => {
console.log("I'm there !!!"); //OUTPUT: I'm there !!!
const { data } = await axios.get(`/items/${match.params.id}`);
console.log("data from useEffect: ", data); //OUTPUT:
setTitle(data.title);
setDescription(data.description);
};
fetching();
console.log("Title: ", title); //OUTPUT: Title: undefined
console.log("Description: ", description); //OUTPUT: Description: undefined
console.log("I'm here !!!"); //OUTPUT: I'm here !!!
}, [match.params.id]);
...
}
后端代碼:
服務器.js
app.use("/items", itemRoutes);
itemRoutes.js
const asyncHandler = require("express-async-handler");
router.route("/:id").get(
asyncHandler(async (req, res) => {
const wantedItem = await Item.findById(req.params.id);
if (wantedItem) {
res.json(wantedItem);
} else {
res.status(404).json({ message: "Requested item is not found!" });
}
res.json(wantedItem);
});
)
和我得到的錯誤:
GET http://localhost:3000/items/614dbaea5338fa8622d8e3df 401 (Unauthorized)
如果有人能幫我找出錯誤,我會很高興
使用掛鈎設置時,您不會直接訪問useEffect
方法中的數據。
例子:
useEffect(() => {
setTitle("This is title");
console.log("Title: ", title); //OUTPUT: Title: undefined
}, [match.params.id]);
您可以添加依賴項並在更改title
值時檢查它
useEffect(() => {
console.log("Title: ", title); //OUTPUT: This is title
}, [title]);
編輯答案
如果 API 拋出 401 意味着Unauthorized
。 您需要在 API 調用中傳遞authentication token
,以驗證來自backend
的 API 請求。
在這里您可以查看如何在 API 調用中傳遞token
。 使用 axios 發送不記名令牌
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.