如何在restify 1.x.x中发布访问数据?

问题描述:

我正在将数据发布到restify API,但无法找到任何有关如何访问发布数据的当前示例。这个怎么用?如何在restify 1.x.x中发布访问数据?

我找到了答案。其中一个插件需要激活,。然后可以在req.params(默认)或req.bodymapParams: false)中找到数据,具体取决于settings(具体请参阅BodyParser部分)。

例子:

server.use(restify.bodyParser({ mapParams: false })); // mapped in req.body 

或者:

server.use(restify.bodyParser()); // mapped in req.params 

很简单:

server.use(restify.bodyParser({ mapParams: false })); 

您需要激活bodyParser中的RESTify

此代码将打印请求正文控制台:

var restify = require('restify'); 
var server = restify.createServer(); 

// This line MUST appear before any route declaration such as the one below 
server.use(restify.bodyParser()); 

server.post('/customer/:id', function (req, resp, next) { 
    console.log("The request body is " + req.body); 
    response.send("post received for customer " + req.params.id + ". Thanks!"); 
    return next(); 
}); 

对于restify 5.0.0+,使用方法:

server.use(restify.plugins.bodyParser()); 

https://github.com/restify/node-restify/issues/1394#issuecomment-312728341

对于旧版本的使用:

server.use(restify.bodyParser()); 

告诉的RESTify后使用bodyParser中间件请求正文将根据请求提供物体属性:

server.post('/article', (req, res, next) => { 
    console.log(req.body) 
    next() 
})