GET http://localhost:5000/api/user/allusers?search=s 401 (Unauthorized)

30 views Asked by At

Issue Description: I'm currently developing a React project where I'm utilizing Axios to make GET requests to my backend API. Within the application, there's a search feature implemented, allowing users to search for users via a request to /api/user/allusers with a search parameter. The frontend should validate user input for the search feature and display a warning if it's empty.

Code Snippet:

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;

Despite providing the token in the request headers, search functionality fails to retrieve results, even though empty inputs are correctly flagged with a warning.

1

There are 1 answers

0
gdurelle On

It is not the tech it is the host URL, you local IP instead of localhost. SO in your get call use:

127.0.0.1:5000

instead of localhost

To get more infos on your error, you can log it:

 .catch(function (error) {
     console.log(error.response.status)
     console.log(error.response.data.error) 
   if(error.response.status==401){
     //redirect to login
   }
 })