2013-04-10 58 views
2

我正在爲圖像發出HTTP GET請求。有時圖像會回到404或403.我很驚訝,我必須明確檢查,而不是在錯誤事件中選擇它。它是如何工作的,還是我在這裏錯過了一些東西?Node.js http獲取請求錯誤事件不拾起404或403

function processRequest(req, res, next, url) { 
    var httpOptions = { 
     hostname: host, 
     path: url, 
     port: port, 
     method: 'GET' 
    }; 

    var reqGet = http.request(httpOptions, function (response) { 
     var statusCode = response.statusCode; 

     // Many images come back as 404/403 so check explicitly 
     if (statusCode === 404 || statusCode === 403) { 
      // Send default image if error 
      var file = 'img/user.png'; 
      fs.stat(file, function (err, stat) { 
       var img = fs.readFileSync(file); 
       res.contentType = 'image/png'; 
       res.contentLength = stat.size; 
       res.end(img, 'binary'); 
      }); 

     } else { 
      var idx = 0; 
      var len = parseInt(response.header("Content-Length")); 
      var body = new Buffer(len); 

      response.setEncoding('binary'); 

      response.on('data', function (chunk) { 
       body.write(chunk, idx, "binary"); 
       idx += chunk.length; 
      }); 

      response.on('end', function() { 
       res.contentType = 'image/jpg'; 
       res.send(body); 
      }); 

     } 
    }); 

    reqGet.on('error', function (e) { 
     // Send default image if error 
     var file = 'img/user.png'; 
     fs.stat(file, function (err, stat) { 
      var img = fs.readFileSync(file); 
      res.contentType = 'image/png'; 
      res.contentLength = stat.size; 
      res.end(img, 'binary'); 
     }); 
    }); 

    reqGet.end(); 

    return next(); 
} 

回答

7

是,它是如何工作的?

是的。 http.get()http.request()不要判斷廣泛響應的內容。他們主要驗證是否收到響應並且採用了有效的格式進行解析。

除了包括測試狀態代碼之外,還可以由您的應用程序執行任何驗證。

+0

是的,這是有道理的。我猜像500這樣的事情會導致它發生錯誤事件? – occasl 2013-04-10 01:36:32

+2

@occasl不一定;這仍然是一個迴應。被拒絕的連接或超時將是一個「錯誤」。 – 2013-04-10 01:37:40