我有一个使用express.js编写的后端,它执行标准的CRUD操作。我使用均衡器作为我的 ORM。这是代码:
import { Sequelize} from 'sequelize';
import User from '../Models/User.js';
import bcrypt from 'bcrypt';
async function getUserByUsername(username) {
try {
// Find a user record with the specified username
const foundUser = await User.findOne({
where: {
username: username
}
});
// Check if the user was found
if (foundUser) {
return true;
} else {
false;
}
} catch (error) {
console.error('Error finding user:', error);
}
}
const sequelizer = new Sequelize.Sequelize({
dialect: 'sqlite',
storage: 'DergiKullanicilar.db'
});
const createUser = async (req,res)=>{
const data = req.body ?? {};
const user = {username : data.username, email:data.email, password:data.password,role:data.role ?? 'user'};
if(!user.username || !user.password)
{res.status(400).json({'message': 'username and password are required'})
return;
}
//check for duplicates
if(await getUserByUsername(user.username)){
res.sendStatus(409).json({"message":"user already exists"});
return;
}
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password,salt);
try {
// Create a new user record with the provided data
const newUser = await User.create(user);
// Return the newly created user record
res.sendStatus(201);
return
} catch (error) {
res.sendStatus(500);
// Handle any errors that occur during the insert operation
console.error('Error creating user:', error);
throw error; // Rethrow the error to be handled by the caller
}
}
export default {createUser};
问题出现在 getUserByUsername 函数调用处,并导致整个系统关闭。其他情况都很好,请求错误,服务器错误等。
您已经快完成了,但我确实发现了一些可能是原因的小问题。
你有:
async function getUserByUsername(username) {
try {
// Find a user record with the specified username
const foundUser = await User.findOne({
where: {
username: username
}
});
// Check if the user was found
if (foundUser) {
return true;
} else {
false; <--- THIS
}
} catch (error) {
console.error('Error finding user:', error);
}
}
.sendStatus
结束响应,因此在其后面链接 json 将不起作用。尝试在链接 .status()
之前使用 json()
。像这样:
if(await getUserByUsername(user.username)){
res.status(409).json({"message": "user already exists"});
return;
}
我希望这对你有用。祝你好运!