0% found this document useful (0 votes)
14 views

Create Node - Js Web Server

This document explains how to create a simple Node.js web server that handles HTTP requests. It discusses importing the HTTP module, creating a server using createServer(), listening for requests on a port, handling requests by checking the URL and sending responses by setting headers and a body. An example server code is provided that returns different HTML responses depending on the requested URL.

Uploaded by

remic48045
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Create Node - Js Web Server

This document explains how to create a simple Node.js web server that handles HTTP requests. It discusses importing the HTTP module, creating a server using createServer(), listening for requests on a port, handling requests by checking the URL and sending responses by setting headers and a body. An example server code is provided that returns different HTML responses depending on the requested URL.

Uploaded by

remic48045
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

7/27/23, 10:22 AM Create Node.

js Web Server

 Previous Next 

Node.js Web Server

In this section, we will learn how to create a simple Node.js web server and handle HTTP requests.

To access web pages of any web application, you need a web server . The web server will handle
all the http requests for the web application e.g IIS is a web server for ASP.NET web applications
and Apache is a web server for PHP or Java web applications.

Node.js provides capabilities to create your own web server which will handle HTTP requests
asynchronously. You can use IIS or Apache to run Node.js web application but it is recommended
to use Node.js web server.

Create Node.js Web Server

Node.js makes it easy to create a simple web server that processes incoming requests
asynchronously.

The following example is a simple Node.js web server contained in server.js file.

server.js  Copy

var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) { // 2 - creating server

//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

In the above example, we import the http module using require() function. The http module is a
core module of Node.js, so no need to install it using NPM. The next step is to call createServer()
method of http and specify callback function with request and response parameter. Finally, call
listen() method of server object which was returned from createServer() method with port number,
to start listening to incoming requests on port 5000. You can specify any unused port here.

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 1/7
7/27/23, 10:22 AM Create Node.js Web Server

Run the above web server by writing node server.js command in command prompt or terminal
window and it will display message as shown below.

C:\> node server.js


Node.js web server at port 5000 is running..

This is how you create a Node.js web server using simple steps. Now, let's see how to handle HTTP
request and send response in Node.js web server.

Too old to learn…


NOW Are you too old to learn
PLAYING programming or coding
at the age… Watch Video

1/4 NgRx…
NgRx is quite tricky to
setup for production
projects,… Watch Video

Wordpress vs…
Wordpress or custom
website, two ways of
choosing… Watch Video

Handle HTTP Request

The http.createServer() method includes request and response parameters which is supplied by
Node.js. The request object can be used to get information about the current HTTP request e.g.,
url, request header, and data. The response object can be used to send a response for a current
HTTP request.

The following example demonstrates handling HTTP request and response in Node.js.

server.js  Copy

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 2/7
7/27/23, 10:22 AM Create Node.js Web Server

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) { //create web server


if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();

}
else if (req.url == "/student") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();

}
else if (req.url == "/admin") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

}
else
res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

In the above example, req.url is used to check the url of the current request and based on that it
sends the response. To send a response, first it sets the response header using writeHead()
method and then writes a string as a response body using write() method. Finally, Node.js web
server sends the response using end() method.

Now, run the above web server as shown below.

C:\> node server.js


Node.js web server at port 5000 is running..

To test it, you can use the command-line program curl, which most Mac and Linux machines have
pre-installed.

curl -i http://localhost:5000

You should see the following response.

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 3/7
7/27/23, 10:22 AM Create Node.js Web Server

HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 8 Sep 2015 03:05:08 GMT
Connection: keep-alive
This is home page.

For Windows users, point your browser to http://localhost:5000 and see the following result.

Node.js Web Server Response

The same way, point your browser to http://localhost:5000/student and see the following result.

Node.js Web Server Response

It will display "Invalid Request" for all requests other than the above URLs.

Sending JSON Response

The following example demonstrates how to serve JSON response from the Node.js web server.

server.js  Copy

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 4/7
7/27/23, 10:22 AM Create Node.js Web Server

var http = require('http');

var server = http.createServer(function (req, res) {

if (req.url == '/data') { //check the URL of the current request


res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});

server.listen(5000);

console.log('Node.js web server at port 5000 is running..')

So, this way you can create a simple web server that serves different responses.

Learn how to create Node.js Web Application in Visual Studio.

Want to check how much you know Node.js?

Start Node.js Test

 Share  Tweet  Share  Whatsapp

 Previous Next 

.NET Tutorials

C#

Object Oriented C#

ASP.NET Core

ASP.NET MVC

LINQ

Inversion of Control

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 5/7
7/27/23, 10:22 AM Create Node.js Web Server

Web API

Database Tutorials

SQL

SQL Server

PostgreSQL

MongoDB

JavaScript Tutorials

JavaScript

TypeScript

jQuery

Angular 11

Node.js

D3.js

Sass

Programming Tutorials

Python

Go lang

HTTPS (SSL)

TutorialsTeacher.com

TutorialsTeacher.com is optimized for learning web technologies step by step. Examples might be simplified to improve
reading and basic understanding. While using this site, you agree to have read and accepted our terms of use and

privacy policy.

 Contact Us

E-mail list

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 6/7
7/27/23, 10:22 AM Create Node.js Web Server

Subscribe to TutorialsTeacher email list and get latest updates, tips & tricks on C#, .Net, JavaScript, jQuery, AngularJS,

Node.js to your inbox.

Email address GO

We respect your privacy.

 2023 TutorialsTeacher.com. All Rights Reserved.

HOME TERMS OF USE PRIVACY POLICY  2023 TutorialsTeacher.com. All Rights Reserved.

https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server 7/7

You might also like