我将数据发布到restify API,但找不到任何有关如何访问发布数据的示例。这是如何工作的?
答案 0 :(得分:45)
我找到了答案。其中一个包含的插件需要激活restify.bodyParser
。然后,可以在req.params
(默认)或req.body
(mapParams: false
)中找到数据,具体取决于settings(具体来看BodyParser部分)。
示例:
server.use(restify.bodyParser({ mapParams: false })); // mapped in req.body
或者:
server.use(restify.bodyParser()); // mapped in req.params
答案 1 :(得分:6)
对于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
中间件后,请求主体将在请求对象的body属性上可用:
server.post('/article', (req, res, next) => {
console.log(req.body)
next()
})
答案 2 :(得分:5)
非常简单:
server.use(restify.bodyParser({ mapParams: false }));
你需要在restify中激活bodyParser
答案 3 :(得分:1)
此代码会将请求正文打印到控制台:
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();
});