2014-03-05 34 views
7

我需要幫助。我將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); 
}); 
+0

'req.body.test'的值是多少? – Gntem

+9

如果你應該應用'Content-Type:application/json'來請求頭文件restify可以自動完成。 – Gntem

+0

@Phoenix你應該添加一個答案,以便我可以upvote它。奇蹟般有效。 – pbkhrv

回答

3

您是否試過使用標準的JSON庫來解析身體作爲json對象?然後,你應該能夠抓住你需要的任何財產。

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

如果你想使用req.params,你應該改變:

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

使用真:

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

必須使用req.params與bodyParser活躍。

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); 
}); 
0

除了下面的答案。 restify 5.0中的最新語法已經改變。

所有你正在尋找的解析器內的restifyrestify.plugins改用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)); 
+0

不需要'restify-plugins',它們全都已經在'restify.plugins'中。 – Nikolai

+0

是的,它現在正在重新調整。我會更新我的答案。 –