尝试检测数据库中的重复项时出现“错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头”

问题描述 投票:0回答:1

我有一个使用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 函数调用处,并导致整个系统关闭。其他情况都很好,请求错误,服务器错误等。

javascript node.js express http-headers
1个回答
0
投票

您已经快完成了,但我确实发现了一些可能是原因的小问题。

  1. 在 getUserByUsername fn 中,如果找不到用户,则不会返回任何内容。

你有:

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);
        }
    }
  1. .sendStatus
    结束响应,因此在其后面链接 json 将不起作用。尝试在链接
    .status()
    之前使用
    json()

像这样:

if(await getUserByUsername(user.username)){
   res.status(409).json({"message": "user already exists"});
   return;
}

我希望这对你有用。祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.