Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTify on Node.js POST body / json

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.

The posted data contains a json body. In it i have keys such as name, date, address, email, etc.

I want to get the name out of the json body. I am trying to do req.body.name but it is not working.

I have also included server.use(restify.bodyParser()); and it is not working.

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);
});
like image 804
Danny BoyWonder Avatar asked Mar 05 '14 20:03

Danny BoyWonder


2 Answers

In addition to below answer . The latest syntax in restify 5.0 has been change .

All the parser that you are looking for is inside restify.plugins instead of restify use restify.plugins.bodyParser

The method to use it is this.

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));
like image 51
Himanshu sharma Avatar answered Sep 21 '22 13:09

Himanshu sharma


If you want to use req.params, you should change:

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

to use true:

server.use(restify.plugins.bodyParser({ mapParams: true }));
like image 38
soundly_typed Avatar answered Sep 20 '22 13:09

soundly_typed