Document
Document
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).
Once Node.js is installed, you can create a simple HTTP server using the built-in http module. Follow
these steps:
Create a new directory for your project and navigate into it.
mkdir my-node-server
cd my-node-server
notepad server.js
Open server.js with your preferred code editor and add the following code:
javascript
Copy code
// Set the response HTTP header to status 200 OK and content type text/html.
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
});
});
node server.js
Now, open a web browser and go to http://127.0.0.1:3000. You should see the following message
displayed in the browser:
To stop the server, press Ctrl + C in the terminal where the server is running.
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.
res.setHeader('Content-Type', 'text/html');
res.statusCode = 200;
res.statusCode = 200;
res.end('<h1>About Us (GET)</h1>');
body += chunk;
});
req.on('end', () => {
res.statusCode = 200;
});
} else {
res.statusCode = 404;
}
});
});
1. Routing:
o We are manually checking the req.method (the HTTP method) and req.url (the route) to handle
different requests.
2. GET requests:
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.
o If the route doesn't match or the method is not handled, we return a 404 error with a message.
node server.js
• Home page (GET): Open a browser and visit http://127.0.0.1:3000/. You should see:
About Us (GET)
<html>
<body>
<fieldset>
<legend>Login Form</legend>
</fieldset>
</form>
</body>
</html>