Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restify 2.6 post data

I just start to try Restify (and NodeJS in general) and I have some trouble to get the users POST data.

I have a basic Node app. On the documentation and some blog posts I read it's as simple as using the queryParser but it's not working. I think the problem is on my CURL command.

Node App:

var restify = require('restify');

function userCreation(request, result, next) {
  console.log(request.body);
  console.log(request.query);
  console.log(request.params);
  result.send({ name: request.params.name });
  return next();
}

var server = restify.createServer({ version: '1.0.0' });
server.use(restify.gzipResponse());
server.use(restify.queryParser());

server.post({ path: '/users', versions: ['1.0.0'] }, userCreation);

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

CURL command:

curl -is -X POST -H 'accept-version: 1.0.0' -d '{ "name": "John" }' http://127.0.0.1:8080/users

curl -is -X POST -H 'accept-version: 1.0.0' -d 'name=John' http://127.0.0.1:8080/users

The response is:

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 2
Date: Fri, 01 Nov 2013 09:40:08 GMT
Connection: keep-alive

{}

And the Node logs are:

restify listening at http://0.0.0.0:8080
undefined
{}
{}

Hope somebody can help me :)

Kevin

like image 696
kdisneur Avatar asked Nov 01 '13 09:11

kdisneur


2 Answers

Use bodyParser instead of of queryParser.

like image 200
smremde Avatar answered Oct 05 '22 08:10

smremde


In order to process JSON documents sent via HTTP POST requests in your RESTful service you will need :

  1. Use bodyParser in your service
  2. Make sure to include the HTTP Header "Content-Type: application/json" when you submit the HTTP POST request

Your CURL command should be something like:

curl -is -X POST -H "Content-Type: application/json" -H "accept-version: 1.0.0" -d '{ "name": "John" }' http://127.0.0.1:8080/users

Your Restify Service code:

var restify = require('restify');

function userCreation(request, result, next) {
  console.log(request.body);
  result.send({
    name: request.body.name
  });
  return next();
}

var server = restify.createServer({
  version: '1.0.0'
});

server.use(restify.gzipResponse());
server.use(restify.bodyParser());

server.post({
  path: '/users',
  versions: ['1.0.0']
}, userCreation);

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

Good Luck!

like image 44
b-s-d Avatar answered Oct 05 '22 08:10

b-s-d