【问题标题】:Not able to get data from AXIOS inside useEffect()无法在 useEffect() 中从 AXIOS 获取数据
【发布时间】: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


【解决方案1】:

使用钩子设置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 调用中传递 tokenSending the bearer token with axios

【讨论】:

  • 问题中的主要问题有点埋没,但它是来自服务器的 401,而不是 React 状态问题。如果它 React 状态问题,则该问题将与stackoverflow.com/questions/41446560/… 重复,不需要自己的答案。
  • axios将401视为错误,不允许解析body,需要根据状态码判断
  • 确实!通过将身份验证令牌传递给我的端点以确保验证来解决它......谢谢!
猜你喜欢
  • 2020-04-21
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 2021-01-31
  • 2021-03-24
  • 1970-01-01
  • 2019-03-05
相关资源
最近更新 更多