Reputation: 381
I'm trying to send a post parameter (key: test, value: somevlaue) using PostMan using restify framework. For this I've used 2 methods and both are not working:
1st one shows this error:
{
"code": "InternalError",
"message": "Cannot read property 'test' of undefined"
}
2nd one (commented) shows only Error: someerror
Am I doing something wrong?
Here's my code:
var restify=require('restify');
var fs=require('fs');
var qs = require('querystring');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var controllers = {};
var server=restify.createServer();
server.post("/get", function(req, res, next){
res.send({value: req.body.test,
error: "someerror"});
//**********METHOD TWO*********************
/*
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var post = qs.parse(body);
res.send({
Data: post.test,
Error: "Someerror"
});
});
}
*/
});
server.listen(8081, function (err) {
if (err)
console.error(err);
else
console.log('App is ready at : ' + 8081);
});
Upvotes: 1
Views: 1285
Reputation: 4860
With restify ^7.7.0, you don't have to require('body-parser') any more. Just use restify.plugins.bodyParser():
var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)
Upvotes: 1
Reputation: 6332
It looks like you might have your bodyparser
set up incorrectly.
According to the docs under the body parser section you set up the parser in this manner:
server.use(restify.bodyParser({
maxBodySize: 0,
mapParams: true,
mapFiles: false,
.....
}));
The default is to map the data to req.params
but you can change this and map it to req.body
by setting the mapParams
option to false
BodyParser
Blocks your chain on reading and parsing the HTTP request body. Switches on Content-Type and does the appropriate logic. application/json, application/x-www-form-urlencoded and multipart/form-data are currently supported.
Upvotes: 0