Handling POSTed data in Restify and Node.js

When creating a webservice using Restify, you may want to be able to handle data POSTed to your API.  Have a look at our article about creating a RESTful webservice in node.js for the basics on setting up the server and routing the requests.  In that article you see that you use the following code to route a POST request to your handler function.


OK, so now all POST requests will be sent to the my_post_handler function.  The problem is that the data being POSTed to the server needs to be properly parsed so that it can be easily handled by your script.  This is where the Restify plugin bodyParser comes into play.  The plugin can be used easily by simply adding the following line of code before your post handler.  So setting up your routes would look something like this.


Restify will now pass the incoming request to the bodyParser plugin first.  bodyParser parses several types of posted content so that it can be easily accessed in the request params.  Now your post handler can look something like this to access fields that were posted.

function my_post_handler(req,res,next) {
	// Get the first_name value from the POSTed data
	var first_name = req.body.first_name;

	// Send back the value they posted
	res.send("You posted a first name of " + first_name);

You can see that the posted fields can now be accessed in req.body.  You need to make sure that the client posting the data is posting a content type for the data.  So, if you are posting json, the client needs to set the content type header to “application/json”.

That’s all there is to it, you’re now accessing POSTed data using restify and node.js.

1 thought on “Handling POSTed data in Restify and Node.js”

  1. This helped me out alot. Here is an example curl statement to post JSON data:

    curl -X POST -H "Content-Type: application/json" -d '{"name":"Joe"}' http://localhost:8080/api

Leave a Comment