SYS-CON MEDIA Authors: Pat Romanski, Liz McMillan, Yeshim Deniz, Elizabeth White, Courtney Abud

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
As Apache Kafka has become increasingly ubiquitous in enterprise environments, it has become the defacto backbone of real-time data infrastructures. But as streaming clusters grow, integrating with various internal and external data sources has become increasingly challenging. Inspection, routing, aggregation, data capture, and management have all become time-consuming, expensive, poorly performing, or all of the above. Elements erases this burden by allowing customers to easily deploy fully man...
IT professionals are also embracing the reality of Serverless architectures, which are critical to developing and operating real-time applications and services. Serverless is particularly important as enterprises of all sizes develop and deploy Internet of Things (IoT) initiatives. Serverless and Kubernetes are great examples of continuous, rapid pace of change in enterprise IT. They also raise a number of critical issues and questions about employee training, development processes, and opera...
The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential. DevOpsSUMMIT at CloudEXPO expands the DevOps community, enable a wide sharing of knowledge, and educate delegates and technology providers alike.
As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility.
This month @nodexl announced that ServerlessSUMMIT & DevOpsSUMMIT own the world's top three most influential Kubernetes domains which are more influential than LinkedIn, Twitter, YouTube, Medium, Infoworld and Microsoft combined. NodeXL is a template for Microsoft® Excel® (2007, 2010, 2013 and 2016) on Windows (XP, Vista, 7, 8, 10) that lets you enter a network edge list into a workbook, click a button, see a network graph, and get a detailed summary report, all in the familiar environment of...
The Kubernetes vision is to democratize the building of distributed systems. As adoption of Kubernetes increases, the project is growing in popularity; it currently has more than 1,500 contributors who have made 62,000+ commits. Kubernetes acts as a cloud orchestration layer, reducing barriers to cloud adoption and eliminating vendor lock-in for enterprises wanting to use cloud service providers. Organizations can develop and run applications on any public cloud, such as Amazon Web Services, Mic...
Because Linkerd is a transparent proxy that runs alongside your application, there are no code changes required. It even comes with Prometheus to store the metrics for you and pre-built Grafana dashboards to show exactly what is important for your services - success rate, latency, and throughput. In this session, we'll explain what Linkerd provides for you, demo the installation of Linkerd on Kubernetes and debug a real world problem. We will also dig into what functionality you can build on ...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. 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 throug...
Technology has changed tremendously in the last 20 years. From onion architectures to APIs to microservices to cloud and containers, the technology artifacts shipped by teams has changed. And that's not all - roles have changed too. Functional silos have been replaced by cross-functional teams, the skill sets people need to have has been redefined and the tools and approaches for how software is developed and delivered has transformed. When we move from highly defined rigid roles and systems to ...
Implementation of Container Storage Interface (CSI) for Kubernetes delivers persistent storage for compute running in Kubernetes-managed containers. This future-proofs Kubernetes+Storage deployments. Unlike the Kubernetes Flexvol-based volume plugin, storage is no longer tightly coupled or dependent on Kubernetes releases. This creates greater stability because the storage interface is decoupled entirely from critical Kubernetes components allowing separation of privileges as CSI components do n...
With container technologies widely recognized as the cloud-era standard for workload scaling and application mobility, organizations are increasingly seeking to support container-based workflows. In particular, the desire to containerize a diverse spectrum of enterprise applications has highlighted the need for reliable, container-friendly, persistent storage. However, to effectively complement today's cloud-centric container orchestration platforms, persistent storage solutions must blend relia...
Applications with high availability requirements must be deployed to multiple clusters to ensure reliability. Historically, this has been done by pulling nodes from other availability zones into the same cluster. However, if the cluster failed, the application would still become unavailable. Rancher’s support for multi-cluster applications is a significant step forward, solving this problem by allowing users to select the application and the target clusters, providing cluster specific data. Ranc...
AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
JFrog, the DevOps technology leader known for enabling liquid software via continuous update flows, was honored today with two prestigious awards as part of DevOps.com's annual DevOps Dozen. The awards recognized both JFrog Artifactory as the "Best DevOps Commercial Solution" and JFrog Co-Founder and CEO, Shlomi Ben Haim, as the "Best DevOps Solution Provider Executive". DevOps.com holds the DevOps Dozen awards annually to recognize the best of the best in the global DevOps marketplace.
Eggplant, the customer experience optimization specialist, announced the latest enhancements to its Digital Automation Intelligence (DAI) Suite. The new capabilities augment Eggplant’s continuous intelligent automation by making it simple and quick for teams to test the performance and usability of their products as well as basic functionality, delivering a better user experience that drives business outcomes.