2013-04-10 157 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