search

Home  >  Q&A  >  body text

Axios POST returns after API call: ERR_EMPTY_RESPONSE

I'm trying to create a registration form in a Node.JS application.

When I make an AXIOS post request, the data is saved to my database, but the actual promise still returns undefined. The payload is populated correctly. To make matters even more confusing, I've basically mirrored my login code in the function and it works perfectly.

The following code is used for registration.

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);

This is my authController with registration 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);
});

Thank you so much.

In my opinion, since my authentication controller is sending a 201 response, this shouldn't happen.

P粉014218124P粉014218124229 days ago498

reply all(1)I'll reply

  • P粉268654873

    P粉2686548732024-04-04 10:37:45

    The

    then() method does not return an awaitable Promise, but instead takes a callback function that will be executed when the request completes. 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.

    Enter 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);
    }

    reply
    0
  • Cancelreply