我在客户端使用请求模块来执行 REST get 请求,其中连接中间件,然后将请求路由到为它提供服务的节点服务器。问题是我在使用请求模块发出请求时尝试使用该选项json:true,因此我不需要解析和验证收到的响应正文。但不幸的是,它没有到达服务器,因为它在中间件(连接)本身中失败并说“无效 JSON”,因为由于请求设置的内容类型,它似乎验证了 JSON(当没有请求正文时)模块。
这是我使用请求模块提出的请求。
  request(
    {
        uri: myurl,
        json: true, //issue area
        headers: {
             //some headers. but no content-type sepcified
        }
    }
    , function (error, response, body) {
        console.log(body); 
        //Here body comes as object if json:true (not for get as it fails in validation at connect middleware itself), else i need to perform JSON.parse(body).
      }); 
这是json请求模块设置中的属性定义(来自文档)。
json - 将 body 设置为 JSON 表示值并添加 Content-type: application/json 标头。此外,将响应正文解析为 json。
但显然这是一个GET请求content-type,我不会设置任何内容(但使用 json:true 选项请求模块似乎是在内部设置它)。
我可以通过下面的 connect 的 json.js 片段来追踪这一点
return function json(req, res, next) {
    if (req._body) return next();
    req.body = req.body || {};
    // check Content-Type
     //This guy fails because content-type is set as application/json by request module internally
    if ('application/json' != utils.mime(req)) return next();
    // flag as parsed
    req._body = true;
    // parse
    limit(req, res, function(err){
      if (err) return next(err);
      var buf = '';
      req.setEncoding('utf8');
      req.on('data', function(chunk){ buf += chunk });
      req.on('end', function(){
    //Here the problem area obviously buf[0] is undefined
        if (strict && '{' != buf[0] && '[' != buf[0]) return next(utils.error(400, 'invalid json'));
        try {
         ......           
显然,这不是 connect 的问题,但它可能是json:true属性提供的不完整功能。我知道我可以使用设置json:false和解析对 javascript 对象的响应(JSON),JSON.parse()但我对其他请求类型(设置 json:true 时)获得了这种灵活性,我不需要手动验证或解析 JSON 到对象,而是我从请求模块的完整回调中获取它作为对象。
我想知道是否有任何其他选项可以让我将响应主体作为对象,而不会出现由连接失败引起的这些问题,或者有关此功能的任何其他信息证明这种行为是合理的json:true(我找不到任何),或任何人使用过的任何其他解决方案,或对此的任何令人满意的解释也值得赞赏!谢谢。