Welcome!

Blog Feed Post

Node.js ABC’s - P is for POST

HTTPMethodsWith the web services that are popping from your corporate networks to the wild-internet, accessing HTTP based resources is becoming a critical component to any and all application development.  One of the more popular API application design styles is Representational State Transfer  (or REST).   REST implementations are typically developed on top of HTTP with the objects you are effecting being in the URI and the actions, or verbs, being the HTTP methods.  The HTTP methods follow the four basic methods of persistent storage as referenced in the CRUD  acronym of Create, Read, Update, and Delete acronym.

The Verbs (Actions)

  • POST - Create new object
  • GET - Read the contents of an existing object
  • PUT - Update an existing object
  • DELETE - Delete an object

The Nouns (Objects)

While the HTTP method defines the action you take, the URI defines the object you wish to act on.  The URI path can be used to specify hierarchy as illustrated in the following set of resources

  • POST /article - create an article
  • PUT /article/10 - update article #10
  • POST /article/10/comment - create a comment on article #10
  • DELETE /article/10/comment/1 - delete comment #1 on article #10

In the above examples, the id's of the objects were included in the URI paths to identify the various specific objects.  This is a typical pattern in API design but it's also possible to include those values as part of the payload in the requests

Sample Client and Server

If you are implementing a Node.js based solution, you will likely come into a spot where you need to write either a HTTP client, HTTP server, or both.  While the different verbs have subtle differences in how you pass data (GET and DELETE pass parameters in the URI, while POST and PUT utilize payload data within the request), I'll focus this article on how to build a simple client and server that accept POST data (for new object creation).

The Server (http-server.js)

The server code for this article is a basic HTTP listener that supports both GET and POST requests.  It logs the request content and then returns a message to the calling application.

var http = require('http');

function requestHandler(request, response) {
  console.log("--------------------------");
  console.log(request.method + ": " + request.url);
  if ( request.method == "POST" ) {
    request.setEncoding('utf8');
    var data = "";
    request.on("data", function(chunk) {
      data += chunk;
    });
    request.on("end", function() {
      console.log("DATA: " + data);
    });
  }
  response.end("Thank you for " + request.method + "ing the uri '" + request.url + "'");
}

var server = http.createServer(requestHandler);

server.listen(8080, function() {
  console.log("Listening on http://localhost");
});

The Client (http-client.js)

The client application illustrates how to make a simple GET request and a POST request with payload data.  The GET request is meant to retrieve a listing of articles, and the POST request will create a comment on an existing article.

var http = require("http");

// GET
var get_options = {
  host: "localhost",
  port: 8080,
  path: "/article"
};

http.get(get_options, function(response) {
  response.setEncoding("utf8");
  console.log("Response status code: " + response.statusCode);
  response.on("data", function(data) {
    console.log("Data: " + data);
  });
});

// POST
var post_data = "{'content': 'Blah Blah Blah'}";
var post_options = {
  host: "localhost",
  port: 8080,
  path: "/article/10/comment",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": post_data.length
  }
};

var request = http.request(post_options, function(response) {
  response.setEncoding("utf8");
  console.log("Response status code: " + response.statusCode);
  response.on("data", function(data) {
    console.log("Data: " + data);
  });
});
request.write(post_data);
request.end();

Running the code

The client and the server programs can be run by loading them with the node runtime

$ node http-server.js
Listening on http://localhost
--------------------------
GET: /article
--------------------------
POST: /article/10/comment
DATA: {'content': 'Blah Blah Blah'}
$ node http-client.js
Response status code: 200
Data: Thank you for GETing the uri '/article'
Response status code: 200
Data: Thank you for POSTing the uri '/article/10/comment'

Conclusion

With the built-in http node package, calling a HTTP POST method is very seamless and you can be well on your way to building a client or server as part of your architectural solution.

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
Interested in leveling up on your Cloud Foundry skills? Join IBM for Cloud Foundry Days on June 7 at Cloud Expo New York at the Javits Center in New York City. Cloud Foundry Days is a free half day educational conference and networking event. Come find out why Cloud Foundry is the industry's fastest-growing and most adopted cloud application platform.
For financial firms, the cloud is going to increasingly become a crucial part of dealing with customers over the next five years and beyond, particularly with the growing use and acceptance of virtual currencies. There are new data storage paradigms on the horizon that will deliver secure solutions for storing and moving sensitive financial data around the world without touching terrestrial networks. In his session at 20th Cloud Expo, Cliff Beek, President of Cloud Constellation Corporation, w...
As enterprise cloud becomes the norm, businesses and government programs must address compounded regulatory compliance related to data privacy and information protection. The most recent, Controlled Unclassified Information and the EU’s GDPR have board level implications and companies still struggle with demonstrating due diligence. Developers and DevOps leaders, as part of the pre-planning process and the associated supply chain, could benefit from updating their code libraries and design by in...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm. In his Day 3 Keynote at 20th Cloud Expo, Chris Brown, a Solutions Marketing Manager at Nutanix, will explore t...
Regardless of what business you’re in, it’s increasingly a software-driven business. Consumers’ rising expectations for connected digital and physical experiences are driving what some are calling the "Customer Experience Challenge.” In his session at @DevOpsSummit at 20th Cloud Expo, Marco Morales, Director of Global Solutions at CollabNet, will discuss how organizations are increasingly adopting a discipline of Value Stream Mapping to ensure that the software they are producing is poised to o...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...
Cloud applications are seeing a deluge of requests to support the exploding advanced analytics market. “Open analytics” is the emerging strategy to deliver that data through an open data access layer, in the cloud, to be directly consumed by external analytics tools and popular programming languages. An increasing number of data engineers and data scientists use a variety of platforms and advanced analytics languages such as SAS, R, Python and Java, as well as frameworks such as Hadoop and Spark...
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 20th Cloud Expo, Tom Eck, Industry Platforms CTO at IBM Cloud, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing developers ...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that Outscale, a global pure play Infrastructure as a Service provider and strategic partner of Dassault Systèmes, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2010, Outscale simplifies infrastructure complexities and boosts the business agility of its customers. Outscale delivers a secure, reliable and industrial strength solution for its customers, which in...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...
In his session at 20th Cloud Expo, Brad Winett, Senior Technologist for DDN Storage, will present several current, end-user environments that are using object storage at scale for cloud deployments including private cloud and cloud providers. Details on the top considerations of features and functions for selecting object storage will be included. Brad will also touch on recent developments in tiering technologies that deliver single solution and an end-user view of data across files and objects...
SYS-CON Events announced today that Tintri, Inc, a leading provider of enterprise cloud infrastructure, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Tintri offers an enterprise cloud platform built with public cloud-like web services and RESTful APIs. Organizations use Tintri all-flash storage with scale-out and automation as a foundation for their own clouds – to build agile development environments...