Node js http Server Example

If you want to create a web server using Node.js, you can utilize the built-in http module. This module provides the functionality necessary to create an HTTP server that can listen to incoming HTTP requests from web browsers or other client applications.

Creating a Basic http Server with Node.js

What is a server and how does Node.js use it?

A server is a software program or hardware device that provides functionality for other programs or devices, called clients. Node.js uses the built-in http module to create a web server. The http module allows Node.js to listen for incoming HTTP requests from clients such as web browsers.

How do you create an HTTP server using Node.js?

To create an HTTP server using Node.js, you first need to import the http module using the require statement. Then you can use the createServer method to create the server and pass in a callback function that will handle incoming HTTP requests.

For example:

const http = require('http');

http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

In this example, we create a simple HTTP server that listens on port 8080. The createServer method takes a callback function that will be called whenever there is an incoming HTTP request. The callback function takes two arguments, request and response, which represent the incoming request and the outgoing response object, respectively.

The response.writeHead method is used to set the status code and the HTTP headers of the response, while the response.end method is used to send the response back to the client with the specified contents.

How do you create an HTTP server that serves an HTML page from a file?

To serve an HTML page from a file using an HTTP server created with Node.js, you can use the fs module to read the HTML file and then send it to the client as the HTTP response.

For example:

const http = require('http');
const fs = require('fs');

http.createServer((request, response) => {
  if (request.url === '/') {
    fs.readFile('index.html', (err, data) => {
      if (err) {
        response.writeHead(404);
        response.end('File not found');
      } else {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(data);
      }
    });
  }
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

In this example, we check if the incoming request URL is the root URL, '/', and if so, we read the contents of the 'index.html' file using the fs.readFile method. If there is an error reading the file, we send a 404 status code to the client. If the file is successfully read, we set the HTTP header to 'text/html' and send the file contents back to the client as the HTTP response.

Handling http Request and Response Objects

What is an HTTP request object and how does it work?

An HTTP request object represents the incoming client request that is received by the HTTP server. It contains information about the request, such as the HTTP method used, the URL requested, and any data submitted with the request. In Node.js, the HTTP request object is passed as the first argument to the callback function for the createServer method.

You can access the properties of the HTTP request object to handle the request in your server code. For example, you can get the URL of the request using the request.url property and extract the query string parameters from it.

How do you create an HTTP request object that contains JSON data?

You can create an HTTP request object that contains JSON data by setting the 'Content-Type' header to 'application/json' and using the JSON.stringify method to convert the JSON object to a string before sending it in the HTTP request body.

For example:

const http = require('http');

const data = {name: 'John Doe', age: 30};
const options = {
  hostname: 'localhost',
  port: 8080,
  path: '/api/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(JSON.stringify(data));
req.end();

In this example, we create an HTTP request object that sends a POST request to '/api/users' with JSON data containing the name and age properties. The options object contains the hostname, port, path, method, and headers of the HTTP request.

We then create an HTTP request using the http.request method and pass in the options and a callback function that will be called when the response is received. We also set up error handling for the request using the 'error' event.

The req.write method is used to send the JSON data in the request body, while the req.end method is used to signal that the HTTP request is complete and should be sent to the server.

How do you handle HTTP responses in Node.js?

In Node.js, you can handle HTTP responses using the response object that is passed as the second argument to the callback function for the createServer method.

You can use the response.writeHead method to set the status code and the HTTP headers of the response, and the response.end method to send the response back to the client with the specified contents.

Creating an HTTP server with Node.js is easy and straightforward using the built-in http module. By handling incoming HTTP requests and sending responses, you can create powerful web applications and APIs that can handle a variety of requests and data formats.

Sources

DigitalOcean

Tutorials Teacher

GeeksforGeeks

Stay up to date

Get notified when I publish New Games or articles, and unsubscribe at any time.

Thanks for joining!

Related video

FAQs

What is a Node js http Server?

A Node js http Server is a web server that uses the http module of Node.js to handle http requests. It allows developers to create a web server and handle client requests using JavaScript.

How can I create an http server using Node.js?

To create an http server using Node.js, you need to use the http module. Here is an example of how to create a basic http server:

`const http = require(‘http’);

const server = http.createServer((req, res) => { res.end(‘Hello World!’); });

server.listen(3000, () => { console.log(’Server running at http://localhost:3000/'); });`

What is a callback function in a Node.js http web Server?

A callback function is a function that is passed as a parameter to another function and is executed after the execution of the parent function. In the context of a Node.js http Server, a callback function is executed when an http request is received.

How can I handle an incoming http request object in a Node.js http Server?

To handle an incoming http request in a Node.js http Server, you need to create an http server using the http module and set up a request listener. Here is an example:

const http = require(‘http’);

const server = http.createServer((req, res) => { // Handle http request here });

server.listen(3000, () => { console.log(’Server running at http://localhost:3000/'); });

How can I send an http response back to the client in a Node.js http Server?

To send an http response back to the client in a Node.js http Server

What is Node.js http Server?

Node.js http Server is a web server, which is used to deliver web pages requested by client apps. It is a module of Node.js that allows developers to create web servers and handle HTTP requests and responses.

How can I import http module in Node.js?

You can import http module in Node.js by using this code: const http = require(‘http’);

How can I create a simple Node.js http server?

You can create a simple Node.js http server by using the following code snippet:

const http = require(‘http’);

http.createServer(function(request, response) { response.writeHead(200, {‘Content-Type’: ‘text/plain’}); response.end(‘Hello World!’); }).listen(8080);

console.log(’Server running at http://localhost:8080/');

How can I start the Node.js server?

You can start the Node.js server by running the command: node server.js

How can I respond with an HTML page from a file in Node.js?

You can load the HTML file from your local directory and return it in the http response by using the following code:

const http = require(‘http’); const fs = require(‘fs’);

http.createServer(function (request, response) { fs.readFile(‘path/to/your/html/file.html’, function(err, data) { response.writeHead(200, {‘Content-Type’: ‘text/html’}); response.write(data); response.end(); }); }).listen(8080);

How can I get the HTTP request in Node.js web server?

You can get the HTTP request in Node.js by using the ‘request’ object like this:

http.createServer(function(request, response) { console.log(request.url); // get the requested url console.log(request.method); // get the request method (GET, POST, etc.) });

How can I handle JSON response data in the HTTP response in Node.js?

You can respond with JSON data in the HTTP response by using the JSON.stringify() method like this:

http.createServer(function(request, response) { const jsonResponse = {‘message’: ‘Hello World!’}; response.writeHead(200, {‘Content-Type’: ‘application/json’}); response.end(JSON.stringify(jsonResponse)); });

How can I set HTTP headers in the response in Node.js?

You can set HTTP headers in the response by modifying the ‘header’ property of the HTTP response object like this:

http.createServer(function(request, response) { response.writeHead(200, {‘Content-Type’: ‘text/plain’}); response.setHeader(‘custom-header’, ‘Hello World!’); response.end(‘Hello World!’); });

How can I handle errors in the Node.js http server?

You can handle errors in the Node.js http server by using the ‘error’ event of the server object and logging the error like this:

http.createServer(function(request, response) { // your server logic }).listen(8080);

server.on(‘error’, function(err) { console.log(‘Server error:’, err.message); });

How can I send an HTTP status code other than 200 in the response in Node.js?

You can send an HTTP status code other than 200 in the response by changing the first argument of the response.writeHead() method like this:

http.createServer(function(request, response) { response.writeHead(404, {‘Content-Type’: ‘text/plain’}); response.end(‘Page not found!’); });

Related articles

Ruslan Osipov
Author: Ruslan Osipov