상세 컨텐츠

본문 제목

[Node] 트러블 슈팅 : MySql Connection Error

IT/프로그래밍

by James Lee. 2018. 9. 22. 19:10

본문

현상

MySql을 사용해서 DB를 조회해오는 함수를 작성하였는데 간헐적으로 아래와 같은 에러가 발생하였다.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
정확하게는 첫 번째 요청은 되고, 두 번째 API 요청은 안 되고, 세 번째 API 요청은 또 되고.. 이런 현상의 반복이었다.
Code
let connection = mysql.createConnection(db_config);

//...

router.post('/login', function (req, res, next) {
    connection.connect();

    //.. logic

    connection.end();
});
Error Log
0|AuthService  | Error: Cannot enqueue Handshake after invoking quit.
0|AuthService  |     at Protocol._validateEnqueue (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/mysql/lib/protocol/Protocol.js:203:16)
0|AuthService  |     at Protocol._enqueue (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/mysql/lib/protocol/Protocol.js:138:13)
0|AuthService  |     at Protocol.handshake (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/mysql/lib/protocol/Protocol.js:51:23)
0|AuthService  |     at Connection.connect (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/mysql/lib/Connection.js:118:18)
0|AuthService  |     at /Users/jongholee/dev/workspace/starter/AuthService/routes/users.js:19:16
0|AuthService  |     at Layer.handle [as handle_request] (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/express/lib/router/layer.js:95:5)
0|AuthService  |     at next (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/express/lib/router/route.js:137:13)
0|AuthService  |     at Route.dispatch (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/express/lib/router/route.js:112:3)
0|AuthService  |     at Layer.handle [as handle_request] (/Users/jongholee/dev/workspace/starter/AuthService/node_modules/express/lib/router/layer.js:95:5)
0|AuthService  |     at /Users/jongholee/dev/workspace/starter/AuthService/node_modules/express/lib/router/index.js:281:22

원인

에러 메세지의 Handshake 부분에 답이 있었다.
Cannot enqueue Handshake after invoking quit.
DB connection의 중복이 원인이었다.
즉, 이미 상단에서 .createConnection() 호출을 진행한 경우에는 .connect 호출은 불필요한 것이다.
If you using the node-mysql module, just remove the .connect and .end. Just solved the problem myself. Apparently they pushed in unnecessary code in their last iteration that is also bugged. You don't need to connect if you have already ran the createConnection call
아래와 같이 DB Connection 을 맺는 부분을 주석 처리해줬더니 정상 동작하는 것을 확인하였다.
router.post('/login', function (req, res, next) {
    // connection.connect();

    //.. logic

    // connection.end();
});


관련글 더보기

댓글 영역