In an Express, we can route to the particular URI (Uniform Resources Identifier) through HTTP Client request method (GET, POST, DELETE, PUT and so on).
const router = express.Router();
Router class: In express have router class, we can use router class method on the HTTP verbs – GET, PUT, DELETE and etc.
The syntax of routes in an Express application − app.method(path, handler) The path is the route at which the request will run and each route can have one or more handler functions, which are executed when the route is matched.
In an example below we are using an express route to access the resources of HTTP get / or root, /about, /contact etc.
Step 1: First create app.js file in root folder, add the following code
Step 2: Define routing for index, /about and /contact page
In root folder create a folder called routes, create following file index.js, about.js and contact.js file. Add the following code in index.js file
Add route code for about.js file
Add route code for contact.js file
NOTE: We can access root file as http://localhost:3000, we can access about page at http://localhost:3000/about
Example 2 : We are accessing the sub path, eg we are accessing the http://localhost:3000/blog/articles/add.
Step 1: In the routes, folder adds a new file called blog.js file to access the routing code for blog and blog/articles/add.
Step 2: Create a folder view in the root folder and add two new files for the template, add_article.pug and layout.pug. Add the following code in layout.pug file
add the following code in add_article.pug file
Example 3: Accessing the particular sub-path like particular articles like http://localhost:3000/manage/books/edit/2
Step 1: We will first add manage.js code of route in routes folder. We can access to http://localhost:3000/manage/books/edit/2, http://localhost:3000/manage/books, http://localhost:3000/manage/books/add
Step 2: In view folder, we will have to add 3 file books.pug, edit_book.pug and edit_book.pug. We will add code for books.pug and same code can be added to other two files.