node中執行sql遇到的Error: write after end錯誤

需要實現的功能:

在注冊前對用戶名及電子郵箱進行驗重。
由于需要明確的返回注冊失敗原因,因此并未使用or, 而是使用了兩次查詢。

代碼如下:

dbutil.query('select id from user where username="拭目以待"', function (err,data){
    if(data.length !== 0){
        goBack('用戶名被占用');
    }
});
dbutil.query('select id from user where email="182209508@qq.com"', function (err,data){
    if(data.length !== 0){
        goBack('該郵箱已注冊');
    }
});
function goBack(msg){
    var errorJSON = {
        status: 'error',
        msg: msg
    };
    res.write(JSON.stringify(errorJSON));
    res.end();
}

執行后的錯誤信息:

Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:426:15)
    at goBack (/Users/baukh/work/baukhZone/exports/userManager.js:109:21)
    at /Users/baukh/work/baukhZone/exports/userManager.js:96:21
    at Query._callback (/Users/baukh/work/baukhZone/dbutil.js:36:33)
    at Query.Sequence.end (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/sequences/Sequence.js:85:24)
    at Query._handleFinalResultPacket (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/sequences/Query.js:144:8)
    at Query.EofPacket (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/sequences/Query.js:128:8)
    at Protocol._parsePacket (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/Protocol.js:280:23)
    at Parser.write (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/Parser.js:74:12)
    at Protocol.write (/Users/baukh/work/baukhZone/node_modules/mysql/lib/protocol/Protocol.js:39:16)

經過排查發現: 同時執行多個數據庫操作,在只有一個返回結果時,將請求跳出就會導至這種[Error: write after end]錯誤。

修改后的代碼:

dbutil.query('select id from user where username="拭目以待"', function (err,data){
    if(data.length !== 0){
        goBack('用戶名被占用');
    }
    else{
        dbutil.query('select id from user where email="182209508@qq.com"', function (err,data){
            if(data.length !== 0){
                goBack('該郵箱已注冊');
            }
        });
    }
});
function goBack(msg){
    var errorJSON = {
        status: 'error',
        msg: msg
    };
    res.write(JSON.stringify(errorJSON));
    res.end();
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • error code(錯誤代碼)=0是操作成功完成。error code(錯誤代碼)=1是功能錯誤。error c...
    Heikki_閱讀 3,452評論 1 9
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • error code(錯誤代碼)=2000是無效的像素格式。error code(錯誤代碼)=2001是指定的驅動...
    Heikki_閱讀 1,860評論 0 4
  • 錯誤:1000 SQLSTATE: HY000 (ER_HASHCHK)消息:hashchk 錯誤:1001 SQ...
    灼灼2015閱讀 23,661評論 0 6
  • 昨天送女兒去美術興趣班以后,我到單位打卡,小坐一會就下班了。同事帶孩子在那邊過周末,沒什么事,我也就不守在那邊了,...
    思言悟語閱讀 210評論 0 0