Axios POST 调用后返回 :ERR_EMPTY_RESPONSE 错误。

huangapple go评论65阅读模式
英文:

Axios POST returning :ERR_EMPTY_RESPONSE after API call

问题

I am attempting to create a signup form in my Node.JS application.
当我进行AXIOS post请求时,数据被保存到数据库,但实际的Promise仍然返回undefined。有效载荷已正确填充。更令人困惑的是,我本质上复制了我的登录功能的代码,而那个功能完美运行。

This is my user router, located at http://127.0.0.1:3000/api/v1/users
这是我的用户路由,位于http://127.0.0.1:3000/api/v1/users

And this is my authController with the signup function.
这是我的authController,其中包含signup函数。

It seems to me that since my auth controller is sending a 201 response, this shouldn't be happening.
在我看来,由于我的auth控制器发送了201响应,这不应该发生。

英文:

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.

答案1

得分: 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);
}

Please note that I have provided the translated code only, as per your request.

英文:

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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

into this :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

console.log(&#39;hello world&#39;, res, &#39;hello&#39;); 

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月15日 10:48:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定