[英]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.