ExpressJs res.json:发送后不能设置标头

时间:2015-08-25 16:05:55

标签: json node.js express

我使用expressjs,我有这样的路线:

router.route('/monitor')
.all(function (req, res, next) {
    next();
}).get(monitor.monitorServers);

一个控制器(称为监视器,具有上述路由器调用的monitorServers功能),这里是控制器的完整代码:

    var argv = require('minimist')(process.argv.slice(2));
var path = require("path");
var config = require(path.resolve(argv.conf));
var bunyan = require('bunyan');
var log = require(path.resolve('./lib/logger')).createLogger;
// create the S3 object
var AWS = require('aws-sdk');

var commonFunctions = require(path.resolve('./lib/functions-common'));
var async = require('async');

/**
 * Monitor the different severs needed by the book server (check if they still running and connected to them)
 * @param req
 * @param res
 */
exports.monitorServers = function (req, res) {
    // Redis Clients
    var redisBs = commonFunctions.createRedisBS();
    var redisMapi = commonFunctions.createRedisMapi();
    var s3 = new AWS.S3();
    // default values for the response
    var status = 200;
    var message = "Ok";
    var errorMessage = "There's was an error in the book service, check the log to see which part";
    async.waterfall([
        /**
         * Check Redis server of the book service
         * @param callback
         */
        function (callback) {
            redisBs.on('ready', function (error) {
                if (error) {
                    log.fatal({part: 'Redis'}, error);
                }
                if (!redisBs.connected) {
                    status = 500;
                    message = errorMessage;
                    log.fatal({part: 'Redis'}, 'Book service failed to connect to its Redis Server');
                }
                callback(null);
            });
        },
        /**
         * Check the redis server of Mapi
         * @param callback
         */
        function (callback) {
            //REDIS MAPI
            redisMapi.on('ready', function (error) {
                if (error) {
                    log.fatal({part: 'Redis'}, error);
                }
                if (!redisBs.connected) {
                    status = 500;
                    message = errorMessage;
                    log.fatal({part: 'Redis Mapi'}, 'Book service failed to connect to Redis Mapi');
                }
                callback(null);
            });

        },
        /**
         * Check the S3 bucket connexion
         */
        function () {
            s3.headBucket({Bucket: config.bucketEnc}, function (error) {
                if (error) {
                    status = 500;
                    message = errorMessage;
                    log.fatal({part: 'AWS S3'}, 'Book service failed to connect to AWS S3 bucket ' + error);
                }
                res.status(status);
                res.json({book_service: message});
            });

        }

    ], function (err) {  // in case of unexpected error
        if (err) {
            log.error("There was an error on monitoring " + err);
            res.end();
        }
    });

};

从控制器正确返回响应,但有时,即使我没有打电话给路线,我也会收到错误说  发送后无法设置标头 错误是在我放置res.json({book_service: message});的行中触发的。您是否知道错误的根源在哪里?

1 个答案:

答案 0 :(得分:0)

您应该在success的最终回调中处理failureasync.waterfall()案例,而不是在水墙流程的中间。

/**
 * Check the S3 bucket connexion
 */
function (callback) {
    s3.headBucket({Bucket: config.bucketEnc}, function (error) {
        if (error) {
            status = 500;
            message = errorMessage;
            log.fatal({part: 'AWS S3'}, 'Book service failed to connect to AWS S3 bucket ' + error);
            callback(error);
        }

        // VERY IMPORTANT TO ENSURE WATERFALL PROCESS CAN FINISH!
        callback(null, {book_service: message});
    });
}

// Final callback of async.waterfall()
function (err, data) {  // in case of unexpected error
    if (err) {
        log.error("There was an error on monitoring " + err);
        res.end();
    } else {
        res.json(data);
    }
}