我正在尝试在 Node.JS 应用程序中创建注册表单。
当我发出 AXIOS post 请求时,数据会保存到我的数据库中,但实际的承诺仍然返回未定义。有效负载已正确填充。更令人困惑的是,我基本上已经在功能中镜像了我的登录代码,并且运行完美。
下面的代码用于注册。
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); } };
这是我的用户路由器,位于 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);
这是我的带有注册功能的 authController。
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); });
非常感谢。
在我看来,由于我的身份验证控制器正在发送 201 响应,因此这种情况不应该发生。
P粉2686548732024-04-04 10:37:45
then()
方法不会返回可等待的 Promise,而是采用一个回调函数,该回调函数将在请求完成时执行。
你需要改变这个:
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.
进入此:
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); }