typescriptnext.js

pass Axios response from server to client


I am trying to use axios to login and passing back the response but the somehow the response is always undefined.

const handleLogin = async (
  e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
) => {
  e.preventDefault();
  await Login(email, password).then((response) => {
    console.log('response' + response);
    router.push('/profile');
  });
};

server code

await axios
  .post(
    'http://127.0.0.1:3333/auth/signin',
    { email: email, password: password },
    { headers: { 'content-type': 'application/x-www-form-urlencoded' } },
  )
  .then((response) => {
    const accessToken = response.data.accessToken || '';
    const refreshToken = response.data.refreshToken || '';
    // localStorage.setItem('access_token', accessToken);
    // localStorage.setItem('refresh_token', refreshToken);
    if (accessToken != '' && refreshToken != '') {
      cookies().set('access_token', accessToken);
      cookies().set('refresh_token', refreshToken);
      console.log('Authenticated successfully:', response.data);
    }
    return response.data;
  })
  .catch((error) => {
    console.error('Authentication failed:', error);
    return { props: error };
  });

Solution

  • Update your code to use async await correctly. You're mixing with it with .then/catch.

    Here is your code updated by using async await correctly, you should be able to see your response data now. Also for error handling try/catch is a nice way to handle errors with async await.

    const handleLogin = async (
      e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
    ) => {
      e.preventDefault();
      const response = await Login(email, password)
       console.log('response' + response);
       router.push('/profile');
    };
    
      try {
        const response = await axios.post(
          'http://127.0.0.1:3333/auth/signin',
          { email: email, password: password },
          { headers: { 'content-type': 'application/x-www-form-urlencoded' } },
        );
    
        const accessToken = response.data.accessToken || '';
        const refreshToken = response.data.refreshToken || '';
        // localStorage.setItem('access_token', accessToken);
        // localStorage.setItem('refresh_token', refreshToken);
        if (accessToken !== '' && refreshToken !== '') {
          cookies().set('access_token', accessToken);
          cookies().set('refresh_token', refreshToken);
          console.log('Authenticated successfully:', response.data);
        }
        return response.data;
      } catch (error) {
        console.error('Authentication failed:', error);
        return { props: error };
      }