skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search