确定GET请求正文

我正在build立一个restAPI使用restify,我需要允许后身获取请求。 我正在使用bodyparser,但它只给出一个string。 我希望它是一个像在普通的职位端点的对象。

我怎样才能把它变成一个对象? 这是我的代码:

const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.get('/endpoint', function (req, res, next) { console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); }); 

restify中的bodyParser不会默认为正在使用GET方法的请求正文parsing有效的JSON(我假定您正在使用)。 您必须在requestBodyOnGet键设置为true的情况下为bodyParser的初始化提供一个configuration对象:

 server.use(restify.bodyParser({ requestBodyOnGet: true })); 

为了确保请求的主体将是JSON,我还build议您检查端点处理程序中的内容types ; 例如:

 const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser({ requestBodyOnGet: true })); server.get('/endpoint', function (req, res, next) { // Ensures that the body of the request is of content-type JSON. if (!req.is('json')) { return next(new restify.errors.UnsupportedMediaTypeError('content-type: application/json required')); } console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); });