需要實(shí)現(xiàn)的功能:
在注冊(cè)前對(duì)用戶(hù)名及電子郵箱進(jìn)行驗(yàn)重。
由于需要明確的返回注冊(cè)失敗原因亩进,因此并未使用or, 而是使用了兩次查詢(xún)。
代碼如下:
dbutil.query('select id from user where username="拭目以待"', function (err,data){
if(data.length !== 0){
goBack('用戶(hù)名被占用');
}
});
dbutil.query('select id from user where email="182209508@qq.com"', function (err,data){
if(data.length !== 0){
goBack('該郵箱已注冊(cè)');
}
});
function goBack(msg){
var errorJSON = {
status: 'error',
msg: msg
};
res.write(JSON.stringify(errorJSON));
res.end();
}
執(zhí)行后的錯(cuò)誤信息:
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)
經(jīng)過(guò)排查發(fā)現(xiàn): 同時(shí)執(zhí)行多個(gè)數(shù)據(jù)庫(kù)操作,在只有一個(gè)返回結(jié)果時(shí),將請(qǐng)求跳出就會(huì)導(dǎo)至這種[Error: write after end]錯(cuò)誤格仲。
修改后的代碼:
dbutil.query('select id from user where username="拭目以待"', function (err,data){
if(data.length !== 0){
goBack('用戶(hù)名被占用');
}
else{
dbutil.query('select id from user where email="182209508@qq.com"', function (err,data){
if(data.length !== 0){
goBack('該郵箱已注冊(cè)');
}
});
}
});
function goBack(msg){
var errorJSON = {
status: 'error',
msg: msg
};
res.write(JSON.stringify(errorJSON));
res.end();
}