今天在开发注册验证码功能的时候出现一个BUG:注册用户名验证重复的时候报错 Can't set headers after they are sent
相关代码块(前端):
1 else if (res.status=='01') { 2 this.identifyCode = ""; 3 this.makeCode(this.identifyCodes, 4); //此行在接收后端数据时候又发送一次请求 4 this.errorTip = '用户已存在'; 5 this.userName = ''; 6 }
相关代码块(后端Node.js):
1 if (doc){ 2 res.json({ //后端响应前端 3 status:"01", 4 msg:'', 5 result:'' 6 }); 7 }
原因在于:浏览器请求一次之后,服务器却返回两次及两次以上的响应。这种容易发生在异步回调中。
解决方案:在每次的请求处理中,一旦服务器返回响应,就及时使用return结束响应,避免返回多次响应。
相关代码块(后端Node.js):
if (doc){ return res.json({ //结束响应 status:"01", msg:'', result:'' }); }