使用Express 4路由器无法获取Content-Type标头

我试图返回不同的内容,基于请求中的Content-Type头:纯文本或JSON对象。 在Express 3.x中,我使用了req.accepted('application/json')来查明用户是否要求使用JSON。 但req.accepted()在4.x中已被弃用。

我试过req.is() – 返回undefined ,而req.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(用CURLtesting)上效果很好,但是一旦我部署到Heroku,我得到:

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

如何获得Express 4中的标题types,并正确处理? Heroku剥夺了标题? 或者也许是那些新的中间件?

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

检查GET请求上的Content-Type是没有意义的。 Content-Type头部定义请求体中的types数据,而GET请求没有主体。 req.is也检查这个,所以在这种情况下也是无用的。

你应该把Accept头设置为来自客户端的application/json ,并在服务器上使用req.accepts('json')来validation客户端是否已经表明它支持JSON。