在Node.js POST body / json上进行RESTify

我需要帮助。 我将json数据发布到我的节点服务器。 节点服务器正在使用RESTify作为其API。 我无法从发布的数据正文获取req.body.name

发布的数据包含一个json主体。 其中我有钥匙,如姓名,date,地址,电子邮件等

我想从json主体中取出名字。 我正在尝试做req.body.name但它不工作。

我还包括server.use(restify.bodyParser()); 它不工作。

我能够req.params.name并分配一个值。 但是,如果我张贴JSON数据如: {'food': 'ice cream', 'drink' : 'coke'} ,我越来越没有定义。 但是,如果我要req.body ,我会得到完整的json主体。 我希望能够专门得到一个像“饮料”,并具有在console.log上显示的项目。

 var restify = require('restify'); var server = restify.createServer({ name: 'Hello World!', version: '1.0.0' }); server.use(restify.acceptParser(server.acceptable)); server.use(restify.jsonp()); server.use(restify.bodyParser({ mapParams: false })); server.post('/locations/:name', function(req, res, next){ var name_value = req.params.name; res.contentType = 'json'; console.log(req.params.name_value); console.log(req.body.test); }); server.listen(8080, function () { console.log('%s listening at %s', server.name, server.url); }); 

如果你想使用req.params ,你应该改变:

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

使用true:

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

你有没有尝试过使用标准的JSON库来parsing身体作为JSON对象? 那么,你应该能够抓住你需要的任何财产。

 var jsonBody = JSON.parse(req.body); console.log(jsonBody.name); 

您必须使用bodyParser激活的req.params。

 var restify = require('restify'); var server = restify.createServer({ name: 'helloworld' }); server.use(restify.bodyParser()); server.post({path: '/hello/:name'}, function(req, res, next) { console.log(req.params); res.send('<p>Olá</p>'); }); server.get({path: '/hello/:name', name: 'GetFoo'}, function respond(req, res, next) { res.send({ hello: req.params.name }); return next(); }); server.listen(8080, function() { console.log('listening: %s', server.url); }); 

除了下面的答案。 在restify 5.0中的最新语法已经改变。

你正在寻找的所有parsing器是restify.plugins而不是restify使用restify.plugins.bodyParser

使用它的方法是这样的。

 const restify = require("restify"); global.server = restify.createServer(); server.use(restify.plugins.queryParser({ mapParams: true })); server.use(restify.plugins.bodyParser({ mapParams: true })); server.use(restify.plugins.acceptParser(server.acceptable));