【问题标题】:Can't get at Content-Type header using Express 4 Router无法使用 Express 4 路由器获取 Content-Type 标头
【发布时间】:2014-05-27 03:02:43
【问题描述】:

我正在尝试根据请求中的 Content-Type 标头返回不同的内容:纯文本或 JSON 对象。在 Express 3.x 中,我使用 req.accepted('application/json') 来确定用户是否请求 JSON。但req.accepted() 在 4.x 中已被弃用。

我尝试了 req.is() - 返回了 undefinedreq.accepts() - 没用。最后,我求助于:

var router = require('express').Router();
router.get('/ping', function(req, res) {
    var serverTime = (new Date()).toLocaleString();
    if(req.get('Content-Type').indexOf('json') !== -1) {
        res.set({'Content-Type': 'application/json'});
        res.send({serverTime: serverTime});
    }
    else {
        res.send('serverTime: ' + serverTime);
    }
});

这在 localhost 上效果很好(用 CURL 测试),但是一旦我部署到 Heroku,我就会得到:

    TypeError: Cannot call method 'indexOf' of undefined at 
    Object.router.get.res.set.Content-Type [as handle]

如何获取 Express 4 中的标头类型并正确处理? Heroku 是否以某种方式剥离了标题?或者可能是那些新的中间件?

更新:我刚刚验证了每次使用 CURL 都有效,在本地和 Heroku 上使用浏览器会为 req.get('Content-Type') 生成 undefined - 所以这不是 Heroku 问题。不过,我需要标题。

【问题讨论】:

    标签: node.js heroku express http-headers


    【解决方案1】:

    GET 请求上检查 Content-Type 没有意义。 Content-Type 标头定义了请求正文中的类型数据,GET 请求没有正文。 req.is 也检查了这个,所以在这种情况下也没用。

    您应该将Accept 标头从客户端设置为application/json,然后在服务器上使用req.accepts('json') 来验证客户端是否表明它支持JSON。

    【讨论】:

    • 谢谢!我想我正在混合标题(并且使用 CURL 进行测试允许我将 Content-Type 甚至添加到 GET,即使它不属于那里)。但是,常规 GET 接受 / 除非另有说明 - 这意味着检查 req.accepts('application/json') 将返回 true。如何唯一测试指定的application/json
    • 好的,最终使用 if(!req.accepts('*/*') && req.accepts('application/json')) { - 感谢您将 m 设置在正确的轨道上!
    • 无需检查*/*req.accepts('json') 就可以了。
    猜你喜欢
    • 2016-06-24
    • 2015-05-05
    • 1970-01-01
    • 2011-06-21
    • 2012-11-02
    • 1970-01-01
    • 2011-07-21
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多