我正在嘗試在 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); }