在Node.js POST主体/json上进行RESTify [英] RESTify on Node.js POST body / json
问题描述
我需要帮助.我正在将json数据发布到我的节点服务器.节点服务器将RESTify用于其API.我无法从已发布数据的正文中获取req.body.name
.
I am in need of help. I am POSTing json data to my node server. The node server is using RESTify for its API. I am having trouble getting req.body.name
from the body of the posted data.
发布的数据包含json正文.在其中,我有诸如姓名,日期,地址,电子邮件等之类的键.
The posted data contains a json body. In it i have keys such as name, date, address, email, etc.
我想从json主体中获取名称.我正在尝试执行req.body.name
,但是它不起作用.
I want to get the name out of the json body. I am trying to do req.body.name
but it is not working.
我还包含了server.use(restify.bodyParser());
,它不起作用.
I have also included server.use(restify.bodyParser());
and it is not working.
我能够req.params.name
并分配一个值.但是,如果我发布json数据,例如:{'food': 'ice cream', 'drink' : 'coke'}
,我将变得不确定.但是,如果执行req.body
,我将得到完整的json正文.我希望能够专门获得诸如饮料"之类的商品,并将其显示在console.log上.
I am able to req.params.name
and assign a value. But if I POST json data like: {'food': 'ice cream', 'drink' : 'coke'}
, I am getting undefined. However, If I do req.body
, I get the full json body posted. I want to be able to specifically get an item like 'drink' and have that show on 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
,则应更改:
If you want to use req.params
, you should change:
server.use(restify.bodyParser({ mapParams: false }));
使用true:
server.use(restify.bodyParser({ mapParams: true }));
这篇关于在Node.js POST主体/json上进行RESTify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!