Sequelize & DB 오류 - Login 부분

Jamkris (승현)·2023년 7월 22일
0

Error

목록 보기
2/3
post-thumbnail

오류

로그인 부분을 구현하고 있었는 데 아래와 같은 오류가 떴다.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

이 오류의 뜻은 [ERR_HTTP_HEADERS_SENT] 서버가 클라이언트에게 두개 이상의 응답을 보낼 때 뜨는 오류이다. 즉, 하나의 응답을 보낸 후 또 다른 응답을 동시에 보내려고 할 때 생기는 오류 입니다.

router.post('/login', async (req, res) => {
    const { userid, password } = req.body;

    const user = await Users.findOne({ where: { userid: userid } });

    if (!user) {
        res.json({ error: '아이디 또는 비밀번호가 일치하지 않습니다.' });
    }

    bcrypt.compare(password, user.password).then((match) => {
        if (!match) res.json({ error: '아이디 또는 비밀번호가 일치하지 않습니다. bcrypt' });

        res.json('로그인 되었습니다.');
    });
});

위 코드는 findOne을 통해 req.body로 userid가 일치하지 않으면 json으로 error: '아이디 또는 비밀번호가 일치하지 않습니다.'을 응답한다.
하지만 이 코드는 여러개의 응답을 보내면

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

한번은 잘 보내지지만 연속으로 두번 보낼 경우에

이와 같은 오류가 뜬다.

수정 후

router.post('/login', async (req, res) => {
    const { userid, password } = req.body;

    const user = await Users.findOne({ where: { userid: userid } });

    if (!user) {
        return res.json({ error: '아이디 또는 비밀번호가 일치하지 않습니다.' });
    }

    bcrypt.compare(password, user.password).then((match) => {
        if (!match) return res.json({ error: '아이디 또는 비밀번호가 일치하지 않습니다. bcrypt' });

        return res.json('로그인 되었습니다.');
    });
});

위 코드 처럼 내보낼 때 return 문을 통해 응답을 하나만 하게 만들면 쉽게 오류를 해결 할 수 있다.

끄읕

profile
Nothing Change If You Don't Try

0개의 댓글