Restify 2.6 post data
Asked Answered
N

2

6

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

Nylanylghau answered 1/11, 2013 at 9:46 Comment(0)
M
2

Use bodyParser instead of of queryParser.

Mulhouse answered 16/1, 2015 at 13:42 Comment(0)
E
1

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!

Escalante answered 22/3, 2015 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.