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);
});
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));
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 }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With