Dan*_*der 10 json node.js restify
我需要帮助.我正在将json数据发布到我的节点服务器.节点服务器正在使用RESTify作为其API.我无法req.body.name从发布的数据中获取内容.
发布的数据包含一个json正文.在其中我有姓名,日期,地址,电子邮件等密钥.
我想把这个名字从json身上拿出来.我试图这样做,req.body.name但它不起作用.
我也包括在内server.use(restify.bodyParser());,但它不起作用.
我能够req.params.name分配一个值.但是,如果我发布json数据,如:{'food': 'ice cream', 'drink' : 'coke'}我正在未定义.但是,如果我这样做req.body,我会发布完整的json身体.我希望能够专门获得像'drink'这样的项目并在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);
});
Run Code Online (Sandbox Code Playgroud)
如果你想使用req.params,你应该改变:
server.use(restify.plugins.bodyParser({ mapParams: false }));
Run Code Online (Sandbox Code Playgroud)
使用true:
server.use(restify.plugins.bodyParser({ mapParams: true }));
Run Code Online (Sandbox Code Playgroud)
您是否尝试过使用标准JSON库将正文解析为JSON对象?然后,您应该可以获取所需的任何属性。
var jsonBody = JSON.parse(req.body);
console.log(jsonBody.name);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25358 次 |
| 最近记录: |