簡體   English   中英

帶有或不帶有請求的結束事件,有什么區別?

[英]With or without the end event for request, what's the difference?

我是Node.js的新手。 我想知道這兩段代碼有什么區別:

var http = require("http");

http.createServer(function(request,response) {
    request.addListener("end", function(){
        console.log(request);
    });

}).listen(8888);

var http = require("http");

http.createServer(function(request,response) {

    console.log(request);

}).listen(8888);

換句話說,由於每次服務器完成接收數據時都會觸發end事件,所以為什么要使用它呢? 一個新手問題。

我不是NodeJS專家,但是從邏輯上來說,以下內容來自文檔。

考慮一個上傳大文件的請求。 當請求第一次到達服務器時,將調用傳遞給createServer的回調。 當請求已完全發送后,將觸發request對象上的end事件(繼承自ReadableStream )。 那將是完全不同的時代。

您的第二個代碼可能無法滿足您的期望,因為console.log(...)會在每次傳入請求時運行。 但是無法判斷請求是否已經完成(即已完全發送到服務器)。
每次關閉連接並完成請求時(即每次有人請求數據時),您的第一個代碼都會運行console.log(...)。 然后,您可以使用傳輸的數據。 因此,您可能想使用(通常在處理請求時使用)是第一個代碼。

如果要將任何數據發送到此服務器,則意味着必須使用該request.listener來獲取該數據。

 var http = require("http");

 http.createServer(function(req,response) { 

 req.on('data', function (chunk) {

      body += chunk;

  });

  req.on('end', function () {

      console.log('POSTed: ' + querystring.parse(body).urDataName);

      var data=querystring.parse(body).urData;//here u can get the incoming data

     });

 }).listen(8888);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM