我需要幫助。我將json數據發佈到我的節點服務器。節點服務器正在將RESTify用於其API。我無法從發佈的數據正文獲取req.body.name
。對Node.js進行RESTify POST body/json
發佈的數據包含一個json主體。在其中我有鑰匙,如姓名,日期,地址,電子郵件等。
我想從json主體中獲得名稱。我正在嘗試做req.body.name
,但它不工作。
我還包括server.use(restify.bodyParser());
它不起作用。
我可以req.params.name
並分配一個值。但是,如果我POST JSON數據如:{'food': 'ice cream', 'drink' : 'coke'}
,我越來越undefined。但是,如果我做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);
});
'req.body.test'的值是多少? – Gntem
如果你應該應用'Content-Type:application/json'來請求頭文件restify可以自動完成。 – Gntem
@Phoenix你應該添加一個答案,以便我可以upvote它。奇蹟般有效。 – pbkhrv