2015-04-01 93 views
0

我在玩一个基本的Node.js服务器(没有框架)。我希望服务器在特定条件下终止请求。这样做的正确方法是什么?我试过request.connection.destroy(),req.removeListener('data')req.removeListener('end'),但服务器继续运行并返回结果。这里是我的一部分:什么是终止Node.js服务器请求的正确方法?

http.createServer(function(req,res){ 
    req.on('data',function(data){ 
     content+=data; 
     if(condition){ 
      req.connection.destroy(); 
      req.removeListener('data'); 
      req.removeListener('end'); 
     } 
    }); 

    req.on('end',function(){= 
     res.writeHead(200,{ 
      'Context-Type':'text/plain', 
     }); 
     res.write(content); 
     res.end(); 
    }); 
}); 

P.S. req.once('end',...)而不是req.on('end',...)是不是更好?其他人似乎都使用on(),这是有原因吗?

编辑: 我改变了if体:

   req.abort(); 
       req.connection.destroy(); 
       req.removeAllListeners('data'); 
       req.removeAllListeners('end'); 

然而,end事件仍被称为(即content仍在被写入)。

+0

不'removeListener'采取监听器本身作为参数? – Bergi 2015-04-01 23:37:47

回答

0

您必须返回任何结果。这只是正确的方法。您的客户端向服务器发送请求,因此需要回答。它可以是状态400,但它必须是。另一种方式,您的客户永远不会意识到该请求已被终止并放慢您的应用程序。

+0

我在部分代码未显示时返回'400' :) – 2015-04-02 00:12:11

相关问题