Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Routing in Node #117

Open
mahfujul-helios opened this issue Mar 31, 2024 · 0 comments
Open

Routing in Node #117

mahfujul-helios opened this issue Mar 31, 2024 · 0 comments

Comments

@mahfujul-helios
Copy link
Collaborator

Routing in Node

What is Routing in Node ?

Routing in Node.js refers to the process of determining how an HTTP request should be handled within a web application. It involves matching the incoming request's URL pattern to specific code blocks or handlers that are responsible for generating an appropriate response.

There are two ways to implement routing in Node which are listed below:

  • Routing without using Express Framework
  • Routing Using Express Framework

Routing without using Express Framework:

For handling all HTTP methods (i.e. GET, POST, PUT, DELETE, etc.) use the app.all() method:

const express = require('express')
const app = express()
app.all('/', function(req, res) {
    console.log('Hello Sir')
    next()   // Pass the control to the next handler
})

The next() is used to hand off the control to the next callback. Sometimes we use app.use() to specify the middleware function as the callback. So, to perform routing with Express.js you have only to load the express and then use the app object to handle the callbacks according to the requirement. Routing without Framework: Using the frameworks is good to save time, but sometimes this may not suit the situation. So, a developer may need to build up their own server without other dependencies. Now create a file with any name using .js extension and follow the steps to perform routing from scratch:

Here we will use the built-in module of node.js i.e. HTTP. So, First load http:

const http = require('http');

Example: The below code example is without using express framework

const http = require('http');

// Create a server object
http.createServer(function (req, res) {

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

	const url = req.url;

	if (url === '/about') {
		res.write(' Welcome to about us page');
		res.end();
	}
	else if (url === '/contact') {
		res.write(' Welcome to contact us page');
		res.end();
	}
	else {
		res.write('Hello World!');
		res.end();
	}
}).listen(3000, function () {
	// The server object listens on port 3000
	console.log("server start at port 3000");
});

Console Output:

co

Browser Output:

bo

Routing Using Express Framework:
Express.js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function called when a request is received. We have different methods of in-app objects for different types of requests. Node has many frameworks to help you to get your server up and running. The most popular is Express.js.

For a GET request using the app.get() method:

const express = require('express')
const app = express()

app.get('/', function(req, res) {
    res.send('Hello Sir')
})

For POST requests use the app.post() method:

const express = require('express')
const app = express()

app.post('/', function(req, res) {
    res.send('Hello Sir')
})

Example: The below code example is using express framework

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
	res.send('Hello World!');
});

app.get('/about', (req, res) => {
	res.send('Welcome to about us page');
});

app.get('/contact', (req, res) => {
	res.send('Welcome to contact us page');
});

app.listen(port, () => {
	console.log(`Server is running on http://localhost:${port}`);
});

console output:

co2

Browser Output:

bo2

conclusion

Routing is a fundamental aspect of web development in Node.js, responsible for directing incoming HTTP requests to the appropriate handlers within a web application. It plays a crucial role in defining how different URLs are mapped to specific functionality, allowing developers to create organized and modular web applications.

Node.js provides various routing frameworks and libraries, with Express.js being the most popular choice. These frameworks simplify the process of defining routes, matching URLs, and handling requests and responses, thereby streamlining the development of web applications.

Routing enables developers to create RESTful APIs, serve dynamic content, handle form submissions, and implement various other functionalities by defining routes for different HTTP methods (GET, POST, PUT, DELETE, etc.) and URL patterns.

By effectively implementing routing in Node.js applications, developers can achieve better code organization, maintainability, and scalability. It allows for the separation of concerns, enabling different parts of the application to be developed, tested, and maintained independently.

Overall, routing is an essential concept in Node.js web development, empowering developers to build powerful and feature-rich web applications that can handle a wide range of HTTP requests and serve dynamic content to clients efficiently and effectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant