我正在为图像发出HTTP GET请求.有时图像会以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');
});
} …Run Code Online (Sandbox Code Playgroud) node.js ×1