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();
}
是的,這是有道理的。我猜像500這樣的事情會導致它發生錯誤事件? – occasl 2013-04-10 01:36:32
@occasl不一定;這仍然是一個迴應。被拒絕的連接或超時將是一個「錯誤」。 – 2013-04-10 01:37:40