美文网首页还在路上让前端飞Web前端之路
node中执行sql遇到的Error: write after

node中执行sql遇到的Error: write after

作者: 前端沐先生 | 来源:发表于2017-04-12 12:36 被阅读1734次

    需要实现的功能:

    在注册前对用户名及电子邮箱进行验重。
    由于需要明确的返回注册失败原因,因此并未使用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();
    }
    

    相关文章

      网友评论

        本文标题:node中执行sql遇到的Error: write after

        本文链接:https://www.haomeiwen.com/subject/hphmattx.html