Node.js http get request error event not picking up 404 or 403
node.js
Solution
Is that how it works?
Yeah. `http.get()` and `http.request()` don't judge the contents of the response extensively. They primarily verify that a response was received and was in a valid format to be parsed.
It'll be up to your application to perform any validation beyond that, including testing the status code.
Problem
I'm making an HTTP GET request for an image. Sometimes images come back as 404 or 403. I was surprised I had to explicitly check for that rather than picking that up in the error event. Is that how it works or am I missing something here? ``` 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(); } ```