Node.js HTTP Module For Example

Gambar node.js maxpixel.net


The 'http' module is a built-in module in Node.js that provides an HTTP server and client for creating network applications. It is designed to be easy to use and efficient, making it a popular choice for building web servers and other networked applications.

Here is an example of using the 'http' module to create a simple HTTP server that listens on port 8080 and responds with "Hello, World!" to every request:

const http = require('http');

const server = http.createServer((request, response) => {
  response.end('Hello, World!');
});

server.listen(8080, () => {
  console.log('Server listening on port 8080');
});

To make an HTTP request using the http module, you can use the http.request() function, which takes an options object and a callback function as arguments. The callback function is called when the response is received from the server.

Here is an example of making an HTTP GET request to an external API and printing the response data to the console:

const http = require('http');

const options = {
  hostname: 'api.example.com',
  path: '/endpoint',
  method: 'GET'
};

const request = http.request(options, (response) => {
  let data = '';

  response.on('data', (chunk) => {
    data += chunk;
  });

  response.on('end', () => {
    console.log(data);
  });
});

request.end();

The http module also provides other functions for creating and sending HTTP requests, such as http.get() and http.post(), which are convenience functions for making GET and POST requests, respectively.

Post a Comment

Lebih baru Lebih lama