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
Use bodyParser
instead of of queryParser
.
In order to process JSON documents sent via HTTP POST requests in your RESTful service you will need :
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!
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