【发布时间】:2021-11-20 09:26:27
【问题描述】:
我正在尝试从 React 的 useEffect() 中的 axios 获取数据。 我测试了它工作正常的后端,但在前端我收到一个错误 401 (Unauthorized)
反应代码:
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]);
...
}
后端代码:
server.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)
如果有人能帮我找出错误,我会很高兴
【问题讨论】:
-
这意味着端点受到保护你确定你不需要一些访问令牌来访问那个端点
-
除了 401 错误之外,您的
console.log语句将永远不会显示数据,因为 A)当您调用它们时它尚未被检索,并且 B)无论如何,它不会在这些变量中(请参阅:stackoverflow.com/questions/41446560/…)。当你设置状态时,你的组件函数会被再次调用,在这个新调用中你会从useState取回状态。
标签: javascript reactjs axios react-hooks get