获取请求 JSON 类型作为缓冲区

Getting Request JSON type as buffer

我有一个处理 JSON 的函数。它由路由处理程序调用。该函数不是获取 JSON 字符串,而是获取 this-

{"type": "Buffer", "data": [123,122,22,....]}

因此,我无法解析 JSON。是什么导致了这个问题?

我正在传递 JSON 例如 -

{"id": "123", "username": "abc",...}

我的代码是-

server.post('/pages', restify.jsonBodyParser(),createPage);
function createPage(req, res, next)
{
   myfunction(req,res);

   next();
}

function myfunction(req,res){
   console.log(req);
}

这是请求头 -

{"authorization":"Basic xxxxxxx","accept":"application/json, application/xml, text/json, text/x-json, text/javascript, text/xml","user-agent":"RestSharp/105.0.1.0","content-type":"Application/Json", "host":"remoteserver.com:xxx","cookie":"sessionid=36yTgWtzpSR4VrvRikTEzfu8wBcPLWTQARtLgT63","content-length":"4246","accept-encoding":"gzip, deflate"}

看起来 Restify 的 body 解析器中间件不喜欢 Application/Json 作为内容类型,它只接受 application/json(AFAIK 是一个错误,因为 mime-types 应该得到处理 case-insensitive;问题已提交 here)。

如果你不能改变客户端,你可以使用一个 Restify 中间件,它将小写 header:

server.use(function(req, res, next) {
  if (typeof req.headers['content-type'] === 'string') {
    req.headers['content-type'] = req.headers['content-type'].toLowerCase();
  }
  next();
});

您必须在使用 restify.jsonBodyParser() 之前包含它。