Easy HTTP POST testing with the request module

GET and POST requests are common in web development. GET is one that you see more often. For example, when you load most web pages, the majority of the requests that comprise the page are GET requests. But sometimes, you need to make a POST request.

Testing a GET request is easy. Testing a POST request is not always so simple because the HTTP request body must include any data you send. An obvious approach is to create a simple HTML page with a form. The problem there is that you need to create an input element for each data property that you want to send in the POST request. This can be tedious.

Node.js is a great tool for this task. In this article, we will see how a small JavaScript file can make an HTTP POST request. This approach may have potential for being useful in an actual application. But for this article, I wanted to point out that any time you need to test a POST end point, you can setup your test using Node.js.

To get started, clone the following git hub repository:

https://github.com/kevinchisholm/easy-http-post-testing-with-the-request-module

(Instructions on how to run the code are available in the Git hub page.)

package.json

{
  "name"         : "easy-http-post-testing-with-the-request-module",
  "version"      : "0.0.1",
  "description"  : "Easy HTTP POST testing with the request module.",
  "author"       : "Kevin Chisholm",
  "dependencies" : {
    "request"    : "latest",
    "body-parser": "^1.15.2",
    "express": "4.14.0"
  }
}

The package.json for this project contains references to the modules needed. We are using the request module, the body-parser module, and the express module.

The Web Server

Example # 1:

//require the express nodejs module
var express = require('express'),
    //set an instance of exress
    app = express(),
    //require the body-parser nodejs module
    bodyParser = require('body-parser');
 
//support parsing of application/json type post data
app.use(bodyParser.json());
 
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true })); 
 
//tell express what to do when the /about route is requested
app.post('/form',function (req, res) {
    //create a json response
    requestAsJson = JSON.stringify(req.body);
 
    //set the appropriate HTTP header
    res.setHeader('Content-Type', 'application/json');
 
    //log the output
    console.log('The POST data received was: ' + requestAsJson);
 
    //send the POST data back as JSON
    res.end(requestAsJson);
});
 
//wait for a connection
app.listen(5000, function () {
  console.log('POST test server is running on port 5000');
});

In example # 1, we have the server code. The focus of this article is not creating the server code, but this is good to review. We need the express module and the body-parser module. Once we have set the references to those modules, we setup the POST route. When the user sends an HTTP POST request to /form, our code will handle this request.

The requestAsJson variable allows us to setup the round-trip. That is, the exact same data from the POST request is what we return as JSON. We set the Content-Type header to be application/json so that the HTTP header will be correct. Note the log the output comment; this is just for demonstration purposes. We then send the response using the res.end method.

The Test Client

Example # 2:

//set a reference to the request module
var request = require('request'),
    //stubs
    postData = {},
    postConfig = {},
    postSuccessHandler = null;
 
//create an object to send as POST data
postData = {
    name:'Don Draper',
    title:'Creative Director',
    company: 'Sterling Cooper'
};
 
//the config for our HTTP POST request
postConfig = {
    url:'http://localhost:5000/form',
    form: postData
};
 
//the HTTP POST request success handler
postSuccessHandler = function (err, httpResponse, body) {
    //look for this message in your JS console:
    console.log('JSON response from the server: ' + body);
};
 
//make the POST request
request.post(postConfig, postSuccessHandler);

In example # 2, we have the test client. This is the focus of the article. We want an easy way to test POST requests. Instead of mocking-up an HTML page with a form, we can use the file test-post.js to test an HTTP POST request.

We set a reference to the request module. No other module needed in this file. The postData variable is an object containing the data for the HTTP POST request. The postConfig variable contains the URL for the HTTP POST request, and a reference to the postData variable. The postSuccessHandler variable is a success handler for the HTTP POST request. Inside of that success handler, you can see a console.log statement. This statement completes the proof of concept. Whatever data sent for the HTTP POST request should be output in that console.log statement.

How to test the example code

  1. Open up two terminal windows (terminal A and terminal B), and make sure that you are in the root of the repository folder.
  2. In terminal A, execute this command: node post-server.js.
  3. In terminal B, execute this command: node test-post.js.
  4. In terminal A, you should see the message: The POST data received was XXX.
  5. In terminal A, you should see the message: JSON response from the server: XXX.

(In each case, XXX represents the data from the HTTP POST request).

NOTE: Go ahead and change the properties of the postData object. You can create more properties if you wish. No matter what you do, you can see the data that you set in that object in the two console.log statements.

Summary

In this article, we learned how to test HTTP POST requests. We used the request module to make an HTTP POST request. There are other ways to go about this, but this approach illustrates how easy it is to leverage Node.js for this task.

Author

Kevin Chisholm

http://blog.kevinchisholm.com

Share This