SYS-CON MEDIA Authors: Liz McMillan, Yeshim Deniz, Elizabeth White, Pat Romanski, William Schmarzo

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
Inzata is a powerful, revolutionary data analytics platform for integrating, exploring, and analyzing data of any kind, from any source, at massive scale. Powerful AI-assisted Modeling and a patented analytics engine help users quickly load, blend and model raw and unstructured data into powerful enterprise data models, actionable real-time analytics and engaging visualizations. Go beyond spreadsheets and slides and compose a powerful narrative about how your business is performing, and how y...
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our signature Power Panels. Our Expo Floor will bring together the leading global 200 companies throughout the world of Cloud Computing, DevOps, IoT, Smart Cities, FinTech, Digital Transformation, and all they entail. As ...
Wasabi is the hot cloud storage company delivering low-cost, fast, and reliable cloud storage. Wasabi is 80% cheaper and 6x faster than Amazon S3, with 100% data immutability protection and no data egress fees. Created by Carbonite co-founders and cloud storage pioneers David Friend and Jeff Flowers, Wasabi is on a mission to commoditize the storage industry. Wasabi is a privately held company based in Boston, MA. Follow and connect with Wasabi on Twitter, Facebook, Instagram and the Wasabi blog...
Updating DevOps to the latest production data slows down your development cycle. Probably it is due to slow, inefficient conventional data management practices to copy data between different developer and test environment. This problem doesn't scale as teams are adopting faster software release cycles. In this session, Dhiraj Sehgal in Product and Solution at Delphix, will talk about DevOps and cloud-focused strategies to update hundreds of developer and test copies with updates from a master...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Most modern computer languages embed a lot of metadata in their application. We show how this goldmine of data from a runtime environment like production or staging can be used to increase profits. Adi conceptualized the Crosscode platform after spending over 25 years working for large enterprise companies like HP, Cisco, IBM, UHG and personally experiencing the challenges that prevent companies from quickly making changes to their technology, due to the complexity of their enterprise. An accomp...
Big Switch's mission is to disrupt the status quo of networking with order of magnitude improvements in network e ciency, intelligence and agility by delivering Next-Generation Data Center Networking. We enable data center transformation and accelerate business velocity by delivering a responsive, automated, and programmable software-dened networking (SDN) fabric-based networking solution. Traditionally, the network has been viewed as the barrier to data center transformation as legacy networkin...
Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throughout enterprises of all sizes. We are offering early bird savings...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereum.
Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism across F5's entire product suite. MacVittie has extensive development and technical architecture experience in both high-tech and enterprise organizations, in addition to network and systems administration expertise. Prior to joining F5, MacVittie was an award-winning technology editor at Network Computing Magazine where she evaluated and tested application-focused technologies including app secu...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history. Unfortunately, there is no single deployment model that solves all of your business goals. You need to maintain the fl...
Only Adobe gives everyone - from emerging artists to global brands - everything they need to design and deliver exceptional digital experiences. Adobe Systems Incorporated develops, markets, and supports computer software products and technologies. The Company's products allow users to express and use information across all print and electronic media. The Company's Digital Media segment provides tools and solutions that enable individuals, small and medium businesses and enterprises to cre...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...