Lesson 05-Node.js Request Methods GET, POST, and RESTful API

GET/POST Requests

Retrieving GET Request Content

const http = require('http');
const url = require('url');
const util = require('util');

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);

Retrieving POST Request Content

const http = require('http');
const querystring = require('querystring');
const util = require('util');

http.createServer(function (req, res) {
  // Define a variable to store the request body
  let post = '';

  // Listen for data events and append incoming chunks to the post variable
  req.on('data', function (chunk) {
    post += chunk;
  });

  // After the end event, parse the post data into a proper POST request format and return it to the client
  req.on('end', function () {
    post = querystring.parse(post);
    res.end(util.inspect(post));
  });
}).listen(3000);

RESTful API

REST (Representational State Transfer) typically leverages widely used protocols and standards such as HTTP, URI, XML (a subset of standard generalized markup language), and HTML (an application of standard generalized markup language). REST commonly uses JSON as the data format.

The following are the four fundamental methods of the REST architecture:

  • GET: Used to retrieve data.
  • PUT: Used to update or add data.
  • DELETE: Used to delete data.
  • POST: Used to add data.
// users.json
{
  "user1": {
    "name": "mahesh",
    "password": "password1",
    "profession": "teacher",
    "id": 1
  },
  "user2": {
    "name": "suresh",
    "password": "password2",
    "profession": "librarian",
    "id": 2
  },
  "user3": {
    "name": "ramesh",
    "password": "password3",
    "profession": "clerk",
    "id": 3
  }
}
const express = require('express');
const app = express();
const fs = require('fs');

app.get('/listUsers', function (req, res) {
  fs.readFile(__dirname + '/' + 'users.json', 'utf8', function (err, data) {
    console.log(data);
    res.end(data);
  });
});

const server = app.listen(8081, function () {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Application instance, accessible at http://%s:%s', host, port);
});
Share your love