Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Last active December 30, 2023 22:09
Show Gist options
  • Save MirzaLeka/8f4fe4ed173a64f73da0863018b34990 to your computer and use it in GitHub Desktop.
Save MirzaLeka/8f4fe4ed173a64f73da0863018b34990 to your computer and use it in GitHub Desktop.
Send, Receive Request and Handle Response in Node.js using HTTP module

HTTP Client in Node.js

Learn how to send a POST request using HTTP/S module in Node.js.

const http = require('http');

const user = {
  name: 'Super Mario',
  level: 94,
  job: 'Plumber'
};

const data = JSON.stringify(user);

const TOKEN = Buffer.from('TOKEN-12345').toString('base64')

const options = {
  hostname: 'localhost',
  port: 3000,
  path: '/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    'X-Authorization': TOKEN
  }
}

const request = http.request(
  options, (response) => {
  console.log('Response Status Code :>> ', response.statusCode);

  response.on('data', (chunk) => {
    console.log(`Data arrived: ${chunk.toString()}`);
  });

  response.on('error', (err) => {
    console.log('Response error :>> ', err);
  })

});

request.write(data);

request.end();

HTTP Server in Node.js

Create a server that accepts the request body, parses it (from Buffer to JavaScript object), then stringifies and sents it back to the client.

const http = require('http');

const server = http.createServer((req, res) => {

  const bodyStream = [];

  req
    .on('data', (chunk) => {
      bodyStream.push(chunk);
    })
    .on('end', () => {
      const bufferData = Buffer.concat(bodyStream);
      const requestBody =  JSON.parse(bufferData);

      console.log('req.headers :>> ', req.headers);

      res.writeHead(201, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(requestBody));
    });

});

server.listen(3000, () => {
  console.log('Server started on localhost:3000!');
})

How to run

If you have Node.js installed on your machine, copy contents of both files and paste into separate files on your machine (e.g. server.js & client.js)

Run the server

Open up a terminal/CMD and run node server.js.

You should see the following message in the console: Server started on localhost:3000!

Run the client

Open up another terminal/CMD and run node client.js.

You should see the messages printing in both windows:

Server console

req.headers :>>  {
  'content-type': 'application/json',
  'content-length': '49',
  'x-authorization': 'VE9LRU4tMTIzNDU=',
  host: 'localhost:3000',
  connection: 'close'
}

Client console

Response Status Code :>>  201
Data arrived: {"name":"Super Mario","level":94,"job":"Plumber"}

To turn off the server, go to terminal/CMD and hit CTRL/CMD+C.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment