Introduction
Express is a popular Node.js web framework. Amongst its functionality, it provides a wrapper for Routing. The Express Router helps in the creation of route handlers. In this tutorial, you will learn how to work with Express Router.
Let's get started.
Create a new directory for your application. Run the command to initialize npm in the directory you just created.
npm init -y
The only dependency you will need is express, so go ahead and install it.
npm install --save express
At the end, your package.json file should look like this.
#package.json { "name": "express-router", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.2" } }
Now create a new file called index.js, which will be your entry file as stated in your package.json.
For now, you just need a basic setup like this:
#index.js const express = require('express') const app = express() app.listen(3000, () => { console.log(`Server running at port 3000`) })
Basic Routing
Start by creating some basic routes as I have below.
#index.js ... const router = express.Router() // 1 router.get('/', (req, res) => { // 2 res.send('This is the homepage!') }) router.post('/contact', (req, res) => { // 3 res.send('This is the contact page with a POST request') }) app.use('/', router) // 4 ...
- An instance of Express Router is created. The instance is set to a variable called router. This variable will be used whenever you want to create a route.
- A new route is defined for the GET method to the root of the application. It is attached to the instance of the Express Router class.
- A new route is defined for the POST method to the contact page of the application. It is attached to the instance of the Express Router class.
- This mounts some middleware that will be used to handle your routes. Here you tell your app that you want to make use of the router (which is the instance of the Express Router) for every request made to the app that corresponds to the path
'/'
. If you fail to mount a path on this middleware, it will be executed for every request made to the app.
Let's say you had the code below instead.
app.use('/user', router)
This will match all the following: /user/profile, user/profile/edit, user/dashboard/article/view, and so on.
Route Methods
In the above code, you attached a route method to an instance of Express Router. The route method is derived from one of the HTTP methods and attached to the instance of the Express Router as you did.
Express supports the following routing methods that correspond to HTTP methods: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, and search.
There is a routing method app.all()
which is not derived from any HTTP method. This routing method gets loaded for functions at a specified path for all request methods.
Say you have the code below in your application.
app.all('/books', (req, res) => { res.send('This accesses the book section') })
This will be executed for requests to "/books" when you are using GET, POST, PUT, or any HTTP request method.
Route Paths
A route path is used to define an endpoint where requests can be made. It does so with the combination of a request method. In Express, route paths can be string patterns or regular expressions.
Here are examples you can add to your index.js file.
#index.js router.get('/about', (req, res) => { res.send('This route path will match to /about') }) router.get('/profile.txt', (req, res) => { res.send('This route will match to /profile.txt') })
Let's see a route path using string patterns.
router.get('/ab+xy', (req, res) => { // 1 res.send('ab+xy') }) router.get('/ab(xy)?z', (req, res) => { // 2 res.send('/ab(xy)?z') })
- The route will match abxy, abbxy, abbbxy, and so on.
- The route will match /abz and /abxyz.
Route Parameters
These are used to capture values that are specified at a certain position in the URL. They are called URL segments. The values captured are made available in the req.params
object, using the name of the route parameter specified in the path as the keys of the values.
Here is an example.
If you have a route path similar to this in your application: /users/:userId/articles/:
articleId
The requested URL will look like this: http://localhost:3000/users/19/articles/104
In the req.params, the following will be available: { "userId": "19", "bookId": "104" }
Go ahead and create a new route in your application, using the route path above.
router.get('/users/:userId/articles/:articleId', (req, res) => { res.send(req.params) })
Start your server and point your browser to http://localhost:3000/users/19/articles/104. You will see the req.params
object displayed in your browser.
The name of the route parameters must be made up of word characters ([A-Za-z0-9_]).
Let's take it further!
Say you want to have a route path called /users/:name
, where the name of the user is passed into the URL and the application displays the name along with a string. How do you think that can be achieved?
Go ahead and try it out on your own first.
Here is what the route should look like.
router.get('/users/:name', (req, res) => { res.send(`Welcome, ${req.params.name}!`) })
When you visit http://localhost:3000/users/vivian, you should see Welcome, vivian! displayed in the browser.
Login Routes
Let's see how to create a login route in Express. Your login routes require two actions on a single route path. The actions will be differentiated by the route method used. Here is how it will look.
router.get('/login', (req, res) => { res.send('This is should lead to the login form') }) router.post('/login', (req, res) => { res.send('This is used in processing the form') })
After doing this, your store form should have an action whose value is the route defined with the HTTP POST method. Here is how it should look.
<form action="/login" method="POST"> </form>
When the submit button of the form gets clicked, the specified router gets called. The difference between both route paths as stated above is the HTTP POST. This is how the application determines which is responsible for handling the data passed through the form.
Another aspect where this can be experienced is in the area of editing and updating resources.
app.route()
app.route()
can be used to create a chain of route handlers for a specific route path.
Using the example of the login route, here is how you will make use of app.route()
.
app.route('/login') .get((res, req) => { res.send('This is should lead to the login form') }) .post((res, req) => { res.send('This is used in processing the form') })
You can add more route handlers than we have above.
Conclusion
At this point, you should know how routing works in Express. You have learned how to set up basic routing, and also how to work with route methods and paths. You saw how to make use of route parameters and retrieve values sent via the URL.
If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available on Envato Market.
With this knowledge, you can go further to build an Express application with complex routing.
No comments:
Post a Comment