Overview
A new routing Router is proposed in ExpressJS 4.0. Router is like a "mini version" express application. It does not introduce views or settings, but provides the route's required API, .use, .get, .param and route.
Sample Application
Let's create an express application with only a few routes and features:
- Basic routing: Home, About
- A routing middleware that prints the request request to the console
- A route with parameters
- A routing middleware that checks special parameters
- A route for login response to GET and POST requests with path/login
- Verification function: Verify the parameters passed to a certain route
Application file architecture
We only need two files:
- // Plug-ins required for building node applications- // Build the startup file for the sample application
We will write the routing code as a file. In the future, in order to make the sample application modular, we will write these routing codes to different files separately, and even define different routing files for different components of the website.
Create a Node app
To create a node application, we need to write a file to define the plugin that node application depends on.
{ "name": "express-router-experiments", "main": "", "dependencies": { "express": "~4.0.0" } }
The following continues to install the dependencies:
$ npm install
Now that we have Express installed, let's continue writing to process the route.
Create a server
We specify the main attribute value in it, so Express will be used as the application's entry file.
// // Basic settings// ============================================== var express = require('express'); var app = express(); var port = || 8080; //Route// ============================================== // Sample routing('/sample', function(req, res) { ('this is a sample!'); }); // We will write our own routes here // Start server// ============================================== (port); ('Magic happens on port ' + port);
Now we can start the server using the command node. We created a route in the Express 3 era. If you open the browser at this time and visit http://localhost:8080/sample, we can see the following text: this is a sample!.
Basic usage ()
Let's write examples of Node application front-end routing together, including Home page and About page.
// ... // Get router instancevar router = (); // Home page routing (http://localhost:8080)('/', function(req, res) { ('im the home page!'); }); // About page routing (http://localhost:8080/about)('/about', function(req, res) { ('im the about page!'); }); // Integrate defined routes into Node applications('/', router); ...
Our previous code uses () to generate a routing instance, define routing rules, and finally integrates this routing instance into the application. Now we can access the Home page through http://localhost:8080 and the About page through http://localhost:8080/about.
Please note: We can change the default root path ('/') in the route defined earlier. If we change ('/', router) to ('/app', router), then the access address of the home page becomes http://localhost:8080/app, and the access address of the about page becomes http://localhost:8080/app/about.
This is a very useful feature, we can use it to create multiple routing instances() and integrate them into our Node application. For example, different routes can be created in a Node application for different functional requirements: a basic route, a route for permission verification, and other API routes. This makes Node applications more modular and easier to scale.
Create routing middleware()
Routing middleware is actually a mechanism that allows certain operations to be performed before a request request is processed. For example, before returning the response data of a request request to the user, we can check whether the user has permission, logs, etc.
Next, we implement a middleware for printing logs. Every time there is a request request, we print a message in the console.
// ... // Get router instancevar router = (); // Routing middleware: Whenever there is a request request, it will be executed(function(req, res, next) { // Print the method and url of the request (, ); // Continue to process the request request and find a matching route next(); }); // Home page routing (http://localhost:8080)('/', function(req, res) { ('im the home page!'); }); // about page routing (http://localhost:8080/about)('/about', function(req, res) { ('im the about page!'); }); // Integrate defined routes into Node applications('/app', router); ...
We use() to define the routing middleware and apply it to all requests to access our Node application. Open the browser and visit http://localhost:8080/app, and we can see the information printed by console: im the home page!.
In code, the order of location of middleware and routes is very important. When a request request arrives, they are executed in sequence in the code. This means that if you write the middleware behind a route, the route will intercept the request request and complete the response, and the middleware will never be executed.
Router with parameters /hello/:name
We want to pass a person's name in the URL and let the NODE application output Hello name! Here you can use a route with parameters.
// ... // Get router instancevar router = (); ... // Routing with parameters (http://localhost:8080/hello/:name)('/hello/:name', function(req, res) { ('hello ' + + '!'); }); // Integrate defined routes into Node applications('/', router); ...
Now we visit http://localhost:8080/hello/holly to see the information displayed on the browser page:
Hello holly!
Create parameter middleware
If you want to verify the name of the person who passed the URL above and make sure that the name complies with the specification, we need to verify the parameter name in the URL in the routing middleware. It has a special name, parameter middleware. We can use() to create it.
// ... // Get router instancevar router = (); ... // Parameter middleware Verify name parameters('name', function(req, res, next, name) { // Check it here ('doing name validations on ' + name); // After verification, we assign the checked name to the req object = name; // Continue to process the request request and find a matching route next(); }); // Routing with parameters (http://localhost:8080/hello/:name)('/hello/:name', function(req, res) { ('hello ' + + '!'); }); // Integrate defined routes into Node applications('/', router);
Now when we access the /hello/:name route, the parameter middleware we wrote will intervene and perform corresponding verification processing. After verification, we assign the checked name to the req object and use it to get the checked name in the corresponding .get route. Open the browser and visit http://localhost:8080/hello/sally. We can see the information displayed by the browser:
Hello sally!
The console prints out:
doing name validations on sally
If you use the RESTful API, you can even verify whether the token is valid to determine whether the user has permission to access.
Chain routing
We can also create routes directly on the app object. Using () can define multiple routing processing functions for one route. For example, you can initiate a get request for the /login route to display the login interface, and you can also initiate a post request for the /login route to submit login form information. We can use this /login route to create this /login route.
// ROUTES // ============================================== ('/login') // Display the login interface (GET http://localhost:8080/login) .get(function(req, res) { ('this is the login form'); }) // Submit login form (POST http://localhost:8080/login) .post(function(req, res) { ('processing'); ('processing the login form!'); }); ...
Summarize
Using routes in Express 4.0, we can define routes more flexibly:
- Define a set of routes using() multiple times
- Use() to divide modules and use() to integrate them
- Preprocessing request requests using routing middleware
- Use the parameter intermediate .param() file to verify the parameters in the URL
- Create a chained route using ()
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.