GET http://localhost:5000/api/user/allusers?search=s 401(未经授权)

问题描述 投票:0回答:1

问题描述: 我目前正在开发一个 React 项目,其中使用 Axios 向我的后端 API 发出 GET 请求。在应用程序中,实现了搜索功能,允许用户通过带有搜索参数的

/api/user/allusers
请求来搜索用户。前端应验证搜索功能的用户输入,并在输入为空时显示警告。

代码片段:

const handleSearch = async () => {
  if (!search) {
    toast({
      title: "Please Enter something in search",
      status: "warning",
      duration: 5000,
      isClosable: true,
      position: "top-left",
    });
    return;
  }

  try {
    setLoading(true);
    const config = {
      headers: {
        "Content-type": "application/json",
        Authorization: `Bearer ${user.token}`, // Corrected header name
      },
      withCredentials: true, // Include credentials in the request
    };
    const { data } = await axios.get(`http://localhost:5000/api/user/allusers?search=${search}`, config); // Error occurs here
    setLoading(false);
    setSearchResult(data);
  } catch (error) {
    toast({
      title: "Error Occured!",
      description: "Failed to Load the Search Results",
      status: "error",
      duration: 5000,
      isClosable: true,
      position: "bottom-left",
    });
    console.log(error);
  }
};

// This is the auth middleware code in the backend:
const isAuthenticatedUser = asyncHandler(async (req, res, next) => {
  const { token } = req.cookies;

  if (!token) {
    return next(new ErrorHandler("Please Login to access this resource", 401));
  }

  const decodedData = jwt.verify(token, process.env.JWT_SECRET);
  req.user = await User.findById(decodedData.id);

  if (!req.user) {
    return next(new ErrorHandler("User does not exist", 401));
  }

  next();
});

module.exports = isAuthenticatedUser;

尽管在请求标头中提供了令牌,但搜索功能仍无法检索结果,即使空输入已正确标记为警告。

reactjs authentication axios jwt token
1个回答
0
投票

这不是技术,而是主机 URL,您的本地 IP 而不是本地主机。所以在你的 get call 中使用:

127.0.0.1:5000

而不是本地主机

要获取有关错误的更多信息,您可以记录它:

 .catch(function (error) {
     console.log(error.response.status)
     console.log(error.response.data.error) 
   if(error.response.status==401){
     //redirect to login
   }
 })
© www.soinside.com 2019 - 2024. All rights reserved.