Express.js app.router() Method
Last Updated :
06 Apr, 2023
Express.js is a Node.js web flexible framework that provides a set of features for mobile and web applications. Express has various methods provided by many developers and one of the methods in Express is a Router which is used to divert the user to different pages of the website base on request.
Syntax :
express.Router([options]);
Parameter: This function accepts the following parameters:
- case sensitive: It enables the case sensitivity means if the route is '/contact' it does not mean that it is the same as '/Contact', '/contact' etc by default it Ignores the case sensitivity.
- mergeParams: This feature is available on express version 4.5.0 and above. You need to pass mergeParams as true if you want to access params from the Parent route via the child route.
- strict: it enables strict Routing it means if the route is '/about' it does not mean that it is the same as '/about/' by default it is the opposite.
Project Setup and Module Installation:
Step 1: You can visit the link to Install express module. You can install this package by using this command.
npm install express
Step 2: After installing the express module, you can check your express version in the command prompt using the command.
npm version express
Step 3: After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Project Structure: It will look like the following.
Project StructureFilename- index.js:
JavaScript
// Requiring module
const express = require('express');
const app = express();
// Port number
const port = process.env.PORT || 4000;
// import router which is exported
// in app.js file
const route = require('./routes/app.js');
// When a request comes from /result
// route.It divert to app.js
app.use('/result', route);
const visit_link = "<a" + " href=" + "/result"
+ 'style="color:green;"'
+ '"text-decoration:none;"'
+ '"text-size:20px" + ">"'
+ "Hello Geeks" + "</a>"
+ "<br> <br> Click Hello Geeks";
// Handling GET Request '/'
app.get('/', function (req, res) {
// Sending the html code as a string
res.send(visit_link);
});
// Server setup
app.listen(port, function (req, res) {
console.log("listen");
});
Router() Method in Express: When your web or mobile application has many routes, a developer can't maintain the code readability, cleanliness, consistency, and correctness by maintaining all the routes in one file. So express developer comes with a greater idea and introduces a method called Router which helps the developer to maintain all the requirements.
In this example project, when the user clicks on the Hello Geeks, it is redirected to http://localhost:4000/result. When the request contains the '/result' route then the server runs the app.js file which is inside the routes folder.
Filename app.js
JavaScript
// Requiring module
const app = require('express')
// Initiate router
const router = app.Router();
// Path Module
const path = require('path');
// Handling GET Request
router.get('/',function(req,res) {
res.sendFile(path.dirname(__dirname)
+ "/index.html")
})
// Exporting router variable
module.exports = router;
Filename- index.html: After the complete execution of the app.js file, it sends an HTML file to that particular route and shows it on the browser.
HTML
<!DOCTYPE html>
<html>
<body>
<img style="margin-left:auto; margin-right:auto;
display: block;width: 50%;" src=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-15.png"
alt="geeksforgeeks" width="500" height="250">
</body>
</html>
Step to run the Application: Run the index.js file by using the following command:
node index.js
Output: Now open the browser and go to http://localhost:4000/, you will get the following output.
Working model of this projectReference: https://expressjs.com/en/5x/api.html#express.router
Similar Reads
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.Basics of Web Development To better understand t
7 min read
HTML Tutorial
CSS Tutorial CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and enhance website presentation. CSS is one of the three main components of a webpage, along with HTML and JavaScript.HTML adds Structure to a web page.JavaScript adds logic to it and CSS makes it visually appealing or
7 min read
JS Tutorial
JavaScript TutorialJavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
8 min read
JSON TutorialJSON (JavaScript Object Notation) is a widely-used, lightweight data format for representing structured data. Used Extensively : Used in APIs, configuration files, and data exchange between servers and clients.Text-based: JSON is a simple text format, making it lightweight and easy to transmit.Human
5 min read
TypeScript TutorialTypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Vue.js TutorialVue.js is a progressive JavaScript framework for building user interfaces. It stands out for its simplicity, seamless integration with other libraries, and reactive data binding.Built on JavaScript for flexible and component-based development.Supports declarative rendering, reactivity, and two-way d
4 min read
jQuery TutorialjQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Front End
React TutorialReact is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
Angular TutorialAngular is a powerful, open-source web application framework for building dynamic and scalable single-page applications (SPAs). Developed by Google, Angular provides a comprehensive solution for front-end development with tools for routing, form handling, HTTP services, and more.Designed for buildin
4 min read
Backend
Node.js TutorialNode.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Express.js TutorialExpress.js is a minimal and flexible Node.js web application framework that provides a list of features for building web and mobile applications easily. It simplifies the development of server-side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.Built on Node.
4 min read
PHP TutorialPHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
8 min read
Laravel TutorialLaravel is an open-source PHP web application framework that has gained immense popularity since its inception in 2011, created by Taylor Otwell. This renowned framework empowers developers to build robust, scalable web applications with remarkable ease. As a developer-friendly framework, Laravel of
3 min read
Database
Web Technologies Questions The following Web Technologies Questions section contains a wide collection of web-based questions. These questions are categorized based on the topics HTML, CSS, JavaScript, and many more. Each section contains a bulk of questions with multiple solutions. Table of Content HTML QuestionsCSS Question
15+ min read