Routing in Node JS
In Node.js, routing isn’t inherently provided. Instead, developers must manually inspect the URL and method of each incoming request to determine how to handle and respond to it appropriately. This means that routing logic needs to be implemented within the application code, typically through conditional statements or frameworks like Express.js, which offer more structured routing capabilities. By checking the URL and method of each request, developers can tailor responses dynamically based on the specific requirements of the application.
// Filename - index.js
// Requiring the module
const http = require('http');
// Creating server object
const server = http.createServer((req, res) => {
const url = req.url;
if(url === '/') {
res.write('<html>');
res.write(
'<head><title>w3wiki</title><head>');
res.write(
'<body><h2>Hello from Node.js server!!</h2></body>');
res.write('</html>');
return res.end();
}
if(url === '/about') {
res.write('<html>');
res.write(
'<head><title>w3wiki</title><head>');
res.write(
'<body><h2>w3wiki- Node.js</h2></body>');
res.write('</html>');
return res.end();
}
});
// Server setup
server.listen(3000, () => {
console.log("Server listening on port 3000")
});
Steps to Run the Server:
node index.js
Output: Open your browser and go to http://localhost:3000/about:
Node vs Express
Node.js and Express are two essential tools in the JavaScript ecosystem, especially for server-side development. While they are often used together, they serve different purposes. This article will explain what Node.js and Express are, their key differences, and when to use each.
Table of Content
- Node JS
- Express JS
- Below are basic examples of creating a server in Node JS & Express JS
- Routing in Express JS
- Routing in Node JS
- Difference between Node JS and Express JS