2014-03-05 5 views
7

도움이 필요합니다. 내 노드 서버에 json 데이터를 게시하고 있습니다. 노드 서 v는 해당 API에 대해 RESTify를 사용 중입니다. 게시 된 데이터 본문에서 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'})를 사용하면 정의되지 않은 상태가됩니다. 그러나, 내가 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 개체로 구문 분석 했습니까? 그런 다음 필요한 모든 속성을 가져올 수 있어야합니다. 당신이 req.params를 사용하려면

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

, 당신은 변경해야합니다 :

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

사실 사용하기 : 당신이 활성 bodyParser와 req.params를 사용해야합니다

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

.

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의 최신 구문이 변경되었습니다. 당신이 찾고있는

모든 파서는이 있습니다 사용 restify.plugins 대신 restify.plugins.bodyParser

사용 restify의 방법 안에 있습니다.

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

예. 이제 다시 복원됩니다. 나는 나의 대답을 업데이트 할 것이다. –

관련 문제