I am getting the error ''res.json() is not a function''

47 Views Asked by At

I am making a fetch call where I am storing the result in res. When I am converting it into json and storing it in a variable by const data = res.json(); it's giving an error. This is my client-side code:

const handleLogin = async (e) =>{
      e.preventDefault();
      try{
        dispatch(signInStart());
        const res = fetch(`${URL}/api/user/login`,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(user),
        });
        
        const data = await res.json();
        if(data.success === false){
            dispatch(signInFailure(data.message));
            return;
        }
        dispatch(signInSuccess(data));
        navigate('/upload');
      } catch(error){
        dispatch(signInFailure(error.message));
      }
  } ;

This is my server side code:

export const login = async(req,res,next) => {
    const { email, password } = req.body;
    try {
        const validUser = await User.findOne({email});  
        if(!validUser) return next(errorHandler(404,"User not found!"));
        const validPassword = bcryptjs.compareSync(password,validUser.password);
        if(!validPassword) return next(errorHandler(401,"Wrong credentials!"));

        const token = jwt.sign({id: validUser._id},process.env.JWT_SECRET);
        const { password: pass, ...rest} = validUser._doc;  // Excluding password from the user data we are getting
        res.cookie('access_token',token,{httpOnly: true, expires:new Date(Date.now() + 25892000000)})
        .status(200).json(rest)  //Expires after 30 days

    }catch(error) {
        next(error);
    }
};

I need the user data in order to make it available across all pages but I can't resolve this error.

2

There are 2 best solutions below

0
W-B On

it looks like you're trying to use your promise value. You should await your fetch call like so:

const res = await fetch(`${URL}/api/user/login`,{
 method: 'POST',
 ...,
});

You should then be able to use await res.json() see more info on usage https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

0
Gaoridang On

The fetch function is asynchronous. Maybe it works with await fetch(). The problem occurred that you called res.json() directly form the Promise (before resolving).

const res = await fetch(`${URL}/api/user/login`, { ... })

I hope it helps.