我正在使用 Node、Express 和 Mongoose 試圖讓這個 POST 請求使用 Postman 作業,但它一直給我 500 狀態錯誤。我還嘗試僅使用用戶名 & 而不是給我預期的 400 狀態錯誤它只是再次給了我一個 500 錯誤。
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const User = require('../models/userModel');
const registerUser = async (req, res) => {
try {
//get the username & password from the req.body
const { username, password } = req.body;
//check if the username is unique
const uniqueCheck = await User.findOne(username);
if (uniqueCheck) {
res.status(403).json('Username already exists');
}
//hash password
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
//check all fields are filled
if (!username || !password) {
res.status(400).json('Please fill in all fields')
} else {
//create user with username & password that is assigned to the hash version of it
const user = await User.create(username, { password: hash });
res.status(201).json(user);
}
} catch (error) {
res.status(500).json({ error: 'Problem registering user' });
}
}
uj5u.com熱心網友回復:
正如我在評論中已經告訴你的那樣,你應該console.error在 catch 塊中添加一個陳述句,以更好地了解問題出在哪里。
此外,如果第一個if匹配,則會向客戶端發送回應,但代碼執行將計數,嘗試再次回復客戶端并給您另一個錯誤。您應該在第一個if塊中回傳以避免它。
檢查以下解決方案以及對相關編輯的評論
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const User = require('../models/userModel');
const registerUser = async (req, res) => {
try {
//get the username & password from the req.body
const { username, password } = req.body;
//check if the username is unique
const uniqueCheck = await User.findOne(username);
if (uniqueCheck) {
return res.status(403).json('Username already exists'); // --> !!! add a return statement here
}
//hash password
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
//check all fields are filled
if (!username || !password) {
res.status(400).json('Please fill in all fields')
} else {
//create user with username & password that is assigned to the hash version of it
const user = await User.create(username, { password: hash });
res.status(201).json(user);
}
} catch (error) {
console.error(error) // --> !!! log errors here
res.status(500).json({ error: 'Problem registering user' });
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524242.html
