[go: up one dir, main page]

0% found this document useful (0 votes)
5 views6 pages

Document

This document provides a step-by-step guide to install Node.js and create a basic HTTP server using the built-in http module. It includes instructions for setting up the server, handling GET and POST requests, and implementing routing for different URLs. Additionally, it offers examples of how to test the server with both GET and POST requests.

Uploaded by

srilathachina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

Document

This document provides a step-by-step guide to install Node.js and create a basic HTTP server using the built-in http module. It includes instructions for setting up the server, handling GET and POST requests, and implementing routing for different URLs. Additionally, it offers examples of how to test the server with both GET and POST requests.

Uploaded by

srilathachina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 6

Install Node.js and create a basic HTTP server using the built-in http module.

1. Install Node.js

On Windows or macOS:

1. Download Node.js: Go to the Node.js official website, and download the latest LTS version for
your operating system.

2. Install Node.js: Run the installer and follow the instructions. This will install both Node.js and
npm (Node's package manager).

3. You can verify the installation by running these commands:

node -v # Check Node.js version

npm -v # Check npm version

Once Node.js is installed, you can create a simple HTTP server using the built-in http module. Follow
these steps:

Step 1: Create a project folder

Create a new directory for your project and navigate into it.

mkdir my-node-server

cd my-node-server

Step 2: Create a server.js file

In your project folder, create a file called server.js.

notepad server.js

Step 3: Write the server code

Open server.js with your preferred code editor and add the following code:

javascript

Copy code

// Load the http module to create an HTTP server.

const http = require('http');

// Define the hostname and port.


const hostname = '127.0.0.1';

const port = 3000;

// Create an HTTP server and handle requests.

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

// Set the response HTTP header to status 200 OK and content type text/html.

res.statusCode = 200;

res.setHeader('Content-Type', 'text/html');

// Send a simple HTML response.

res.end('<h1>Hello, world! This is my first Node.js server!</h1>');

});

// Make the server listen on the specified port and hostname.

server.listen(port, hostname, () => {

console.log(`Server running at http://${hostname}:${port}/`);

});

Step 4: Run the server

In your terminal, run the following command to start the server:

node server.js

You should see output like:

Server running at http://127.0.0.1:3000/

Step 5: Open the server in a browser

Now, open a web browser and go to http://127.0.0.1:3000. You should see the following message
displayed in the browser:

Hello, world! This is my first Node.js server!


3. Stopping the server

To stop the server, press Ctrl + C in the terminal where the server is running.

Experiment with routing and handling different HTTP methods (GET,POST)

To experiment with routing and handling different HTTP methods (such as GET and POST), you'll need to
expand your basic HTTP server. This involves inspecting the request method (req.method) and the
request URL (req.url) to handle different routes and methods.

Below is an updated version of your server.js file that handles different HTTP methods (GET, POST) and
different routes.

Steps to implement routing and handle different HTTP methods

1. Update server.js to handle routing

const http = require('http');

// Define the hostname and port.

const hostname = '127.0.0.1';

const port = 3000;

// Create an HTTP server to handle requests.

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

// Set a default content-type for the response.

res.setHeader('Content-Type', 'text/html');

// Handle GET requests for the home page

if (req.method === 'GET' && req.url === '/') {

res.statusCode = 200;

res.end('<h1>Welcome to the Home Page (GET)</h1>');


// Handle GET requests for the "/about" route

} else if (req.method === 'GET' && req.url === '/about') {

res.statusCode = 200;

res.end('<h1>About Us (GET)</h1>');

// Handle POST requests for the "/submit" route

} else if (req.method === 'POST' && req.url === '/submit') {

let body = '';

// Collect the data sent with the POST request

req.on('data', chunk => {

body += chunk;

});

// Once the request body has been fully received

req.on('end', () => {

res.statusCode = 200;

res.end(`<h1>Form Submitted (POST)</h1><p>Received Data: ${body}</p>`);

});

// Handle other undefined routes

} else {

res.statusCode = 404;

res.end('<h1>404 - Page Not Found</h1>');

}
});

// Start the server and listen on the defined port

server.listen(port, hostname, () => {

console.log(`Server running at http://${hostname}:${port}/`);

});

Breakdown of the code:

1. Routing:

o We are manually checking the req.method (the HTTP method) and req.url (the route) to handle
different requests.

o We handle different routes like /, /about, and /submit.

o We respond differently based on the HTTP method (GET or POST).

2. GET requests:

o For GET requests to /, we respond with a welcome message.

o For GET requests to /about, we show an "About Us" message.

3. POST requests:

o For POST requests to /submit, we read the request body, collect the data (if any), and then
respond with the submitted data.

o We use req.on('data', ...) to collect the data chunks and req.on('end', ...) to finalize the response
after receiving all the data.

4. Fallback for 404:

o If the route doesn't match or the method is not handled, we return a 404 error with a message.

2. Run the server

Run the server as you did before:

node server.js

You should see the following output:

Server running at http://127.0.0.1:3000/


3. Test the server

Test GET requests:

• Home page (GET): Open a browser and visit http://127.0.0.1:3000/. You should see:

Welcome to the Home Page (GET)

• About page (GET): Visit http://127.0.0.1:3000/about. You should see:

About Us (GET)

Test POST requests:

<html>

<body>

<form action="http://localhost:3000/submit" method="post">

<fieldset>

<legend>Login Form</legend>

<label>Enter UserName:<label><input type="text" name="userName"><br>

<label>Enter Password:</label><input type="password" name="password"><br>

<input type="submit"><input type="Reset">

</fieldset>

</form>

</body>

</html>

You might also like