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_阅读 8,730评论 1 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,473评论 19 139
  • error code(错误代码)=2000是无效的像素格式。error code(错误代码)=2001是指定的驱动...
    Heikki_阅读 6,120评论 0 4
  • 错误:1000 SQLSTATE: HY000 (ER_HASHCHK)消息:hashchk 错误:1001 SQ...
    灼灼2015阅读 23,805评论 0 6
  • 昨天送女儿去美术兴趣班以后,我到单位打卡,小坐一会就下班了。同事带孩子在那边过周末,没什么事,我也就不守在那边了,...
    思言悟语阅读 1,488评论 0 0