Node Express 4中间件缺少标头

时间:2014-04-25 00:26:15

标签: json node.js express content-type middleware

我有一个中间件功能,使用Node的Express4记录每个请求&调试响应。我在请求处理程序中使用res.json调用将JSON发送回客户端以用于除静态文件之外的所有文件。所以我不想记录静态文件的响应,只记录JSON响应。我有以下代码:

function logRequests(req, res, next) {
    // do logging (will show user name before authentication)
    logger.reqLog('IN  '+req.method+' '+req.url, req);

    var oldEnd   = res.end,
        oldWrite = res.write,
        chunks   = [];

    res.write = function(chunk) {
        chunks.push(chunk);
        oldWrite.apply(res, arguments);
    };

    res.end = function(chunk, encoding) {
        if(chunk) {
            chunks.push(chunk);
        }
        oldEnd.apply(res, arguments);

        // the content-type prints "undefined" in some cases
        // even though the browser shows it returned as "application/json"
        console.log('type='+res.get('content-type'));

        if(res.get('content-type') === 'application/json') {
            var body = Buffer.concat(chunks).toString('utf8');
            logger.info(body, req);
        }
        logger.reqLog('OUT '+req.method+' '+req.path, req);
    };
    next(); // make sure we go to the next routes and don't stop here
}

那么为什么有些请求会在中间件中显示正确的内容类型,这意味着他们也会将响应打印得很好而其他请求却没有?在检查返回的头文件时,它们在REST客户端中看起来都很好。

编辑:今晚发现的更多信息在尝试解决这个问题时 - 如果我将任何字符附加为虚拟请求参数,它会正确记录响应类型:

http://localhost:8081/node/ionmed/api/logout?0   WORKS

,其中

http://localhost:8081/node/ionmed/api/logout     DOES NOT

此外,如果我用.end()替换.json()调用,我总是可以在中间件函数中获取响应类型,这样:

    res.json({ item: 'logout', success: true });

变为:

    res.set('content-type', 'application/json');
    res.end({ item: 'logout', success: true });

0 个答案:

没有答案
相关问题