-1

I am attempting to create a signup form in my Node.JS application.

When I make AXIOS post request, the data is persisted to my database but the actual promise still returns undefined. The payload is properly populated. What is even more confusing is that I've essentially mirrored the code for my login in functionality and that works perfectly.

Code below is for the signup.

import axios from 'axios';
import { showAlert } from './alerts';

export const signup = async (name, email, password, passwordConfirm) => {
  try {
    const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/signup',
      data: {
        name,
        email,
        password,
        passwordConfirm,
      },
    }) // res returns undefined.

    if (res.data.status === 'success') {
      showAlert('success', 'Signed up successfully!');
      window.setTimeout(() => {
        location.assign('/login');
      }, 1500);
    }
  } catch (err) {
    showAlert('error', err.response.data.message);
  }
};

This is my user router, located at http://127.0.0.1:3000/api/v1/users

const authController = require('./../controllers/authController');
// const reviewController = require('./../controllers/reviewController');

const router = express.Router();

router.post('/signup', authController.signup);

And this is my authController with the signup function.


const signToken = (id) => {
  return jwt.sign({ id: id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const createSendToken = (user, statusCode, res) => {
  const token = signToken(user._id);
  const cookieOptions = {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
  };

  if (process.env.NODE_ENV === 'production') cookieOptions.secure = true;

  res.cookie('jwt', token, cookieOptions);

  // Remove password from output
  user.password = undefined;

  res.status(statusCode).json({
    status: 'success',
    token,
    data: {
      user,
    },
  });
};

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
    passwordChangedAt: req.body.passwordChangedAt,
    role: req.body.role,
  });
  const url = `${req.protocol}://${req.get('host')}/me`;
  await new Email(newUser, url).sendWelcome();

  createSendToken(newUser, 201, res);
});

Thanks so much.

It seems to me that since my auth controller is sending a 201 response, this shouldn't be happening.

  • `since my auth controller is sending a 201 response, this shouldn't be happening` why do you imagine that? – Jaromanda X May 15 '23 at 03:04
  • 1
    `.then(console.log('hello world', res, 'hello'))` is executed immediately - you'd want the console.log without the .then – Jaromanda X May 15 '23 at 03:06
  • What **exactly** does `res returns undefined` mean? How are you verifying that? Are you getting any error messages? – Phil May 15 '23 at 03:36

1 Answers1

1

The then() method does not return a promise that can be awaited, but instead takes a callback function that will be executed when the request is complete. you need to change this:

 const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/signup',
      data: {
        name,
        email,
        password,
        passwordConfirm,
      },
    }).then(console.log('hello world', res, 'hello')); // res returns undefined.

into this :

const res = await axios({
  method: 'POST',
  url: 'http://127.0.0.1:3000/api/v1/users/signup',
  data: {
    name,
    email,
    password,
    passwordConfirm,
  },
});

console.log('hello world', res, 'hello'); 

if (res.data.status === 'success') {
  showAlert('success', 'Signed up successfully!');
  window.setTimeout(() => {
    location.assign('/login');
  }, 1500);
}