3

画像の 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');
            });

        } 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();
}
4

1 に答える 1

8

それがどのように機能するのですか?

うん。応答の内容を広範に判断http.get()http.request()ないでください。これらは主に、応答が受信され、解析できる有効な形式であったことを確認します。

ステータスコードのテストなど、それ以上の検証を実行するのはアプリケーション次第です。

于 2013-04-10T01:33:53.627 に答える