RESTify on Node.js POST body / json

蹲街弑〆低调 提交于 2019-12-01 03:35:53

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

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

to use true:

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

Have you tried using the standard JSON library to parse the body as a json object? Then, you should be able to grab whatever property you need.

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

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

you must use req.params with bodyParser active.

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);
});
var restify = require('restify')
const restifyBodyParser = require('restify-plugins').bodyParser;
function respond(req, res, next) {
    console.log(req.body)
    const randomParam = req.body.randomParam
    res.send(randomParam);
    next();
}

var server = restify.createServer();
server.use(restifyBodyParser());
server.post('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

... Is what worked for me with restify version 8.3.2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!