Node. js development-detailed sample code for express routing and Middleware

Source: Internet
Author: User
This article mainly introduces nodejs development-express routing and middleware. I think it is quite good. I will share it with you and give you a reference. Let's take a look at it with a small Editor. This article mainly introduces nodejs development-express routing and middleware. The small editor thinks it is quite good. Now I will share it with you and give you a reference. Let's take a look at it with xiaobian.

Routing

Generally, the http url format is as follows:

host[:port][path]

Http indicates the protocol.

Host indicates the host.

Port is a port. It is an optional field. If it is not provided, the default value is 80.

Path specifies the URI (Uniform Resource Identifier) of the requested Resource. If path is not provided in the URL, the default value is "/" (usually supplemented by browsers or other HTTP clients ).

The so-called routing is how to process the path section in the HTTP request. For example, if the URL "xxx.com/users/profile#" is selected, the user will decide to process the URL" /users/profile=.

Let's review the HelloWorld code of the Express version provided in Node. js development-express installation and use:

var express = require('express');var app = express();app.get('/', function (req, res) { res.send('Hello World!');});app.listen(8000, function () { console.log('Hello World is listening at port 8000');});

The app in the code above. the get () call actually adds a route for our website. The "/" path is specified by the Function Represented by the second get parameter.

Express objects can specify routes for common HTTP methods. The following method is used:

app.METHOD(path, callback [, callback ...])

Route path

Example of a routing path using a string:

// Request app that matches the root path. get ('/', function (req, res) {res. send ('root') ;}); // request app that matches the/about path. get ('/about', function (req, res) {res. send ('about') ;}); // match/random. text path request app. get ('/random. text', function (req, res) {res. send ('random. text ');}); example of a routing path in string mode: // match acd and abcdapp. get ('/AB? Cd', function (req, res) {res. send ('AB? Cd ');}); // matches apps such as abcd, abbcd, and abbbcd. get ('/AB + Cd', function (req, res) {res. send ('AB + Cd') ;}); // matches apps such as abcd, abxcd, abRABDOMcd, and ab123cd. get ('/AB * Cd', function (req, res) {res. send ('AB * Cd') ;}); // match/abe and/abcdeapp. get ('/AB (cd )? E ', function (req, res) {res. send (' AB (cd )? E ');});

Character? , +, *, And () are the subsets of regular expressions.-And. are interpreted according to the nominal value in the string-based path.

Example of a routing path using a regular expression:

// Match the path containing a in any path: app. get (/a/, function (req, res) {res. send ('/a/') ;}); // matches butterfly, dragonfly, and does not match apps such as butterflyman and dragonfly man. get (/. * fly $/, function (req, res) {res. send ('/. * fly $ /');});

Route handle

Multiple callback functions can be provided for request processing, and their behavior is similar to that of middleware. The only difference is that these callback functions may call the next ('route ') method and skip other route callback functions. You can use this mechanism to define preconditions for a route. If it makes no sense to continue executing on an existing path, you can give control to the remaining path.

The routing handle can be a function, a function array, or a combination of the two, as shown below.

Use a callback function to process a route:

app.get('/example/a', function (req, res) { res.send('Hello from A!');});

Use multiple callback functions to process routes (remember to specify the next object ):

app.get('/example/b', function (req, res, next) { console.log('response will be sent by the next function ...'); next();}, function (req, res) { res.send('Hello from B!');});

Use the callback function array to process routes:

var cb0 = function (req, res, next) { console.log('CB0'); next();}var cb1 = function (req, res, next) { console.log('CB1'); next();}var cb2 = function (req, res) { res.send('Hello from C!');}app.get('/example/c', [cb0, cb1, cb2]);

Use a combination of functions and function arrays to process routes:

var cb0 = function (req, res, next) { console.log('CB0'); next();}var cb1 = function (req, res, next) { console.log('CB1'); next();}app.get('/example/d', [cb0, cb1], function (req, res, next) { console.log('response will be sent by the next function ...'); next();}, function (req, res) { res.send('Hello from D!');

The METHOD can be lower-case for HTTP methods such as GET and POST, such as app. get and app. post. The path part can be either a string literal or a regular expression. The simplest example is to change the parameter '/' called by app. get () in the previous code to '*', which has different meanings. Before modification, "Hello World!" will be returned only when access in the form of "localhost: 8000" or "localhost: 8000 !", After modification, access like "localhost: 8000/xxx/yyyy. zz" will also return "Hello World !".

When using express to build a Web server, a very important part of the work is to decide how to respond to a request for a specific path, that is, route processing.

The most direct route configuration method is to call the app. get (), app. post () is a one-by-one configuration, but for websites that need to process a large number of routes, this will lead to a new life. Therefore, we need to combine the Routing Parameters (query string, regular expression, custom parameters, and post parameters) in actual development to reduce the workload and improve maintainability.

Middleware

Express has a middleware concept. The so-called middleware is some of the functions executed at this stage after receiving the request and before sending the response.

To insert middleware to the processing chain of a route, you can use the use method of the express object. The method is prototype as follows:

app.use([path,] function [, function...])

When app. use does not provide the path parameter, the default path is "/". When you install middleware for a path, the middleware will be applied when the path based on this path is accessed. For example, if you set the middleware for "/abcd", the middleware will also be applied when "/abcd/xxx" is accessed.

The prototype of the middleware function is as follows:

function (req, res, next)

The first parameter is the Request object req. The second parameter is the Response object res. The third is the next function used to drive the middleware call chain. If you want the later middleware to continue processing the request, you need to call the next method.

A typical call to a path Application Middleware function is as follows:

app.use('/abcd', function (req, res, next) { console.log(req.baseUrl); next();})

App. static Middleware

Express provides a static middleware that can be used to process GET requests for static files on the website and can be accessed through express. static.

The usage of express. static is as follows:

express.static(root, [options])

The first parameter root is the root directory of the static resource to be processed. It can be an absolute or relative path. The second optional parameter is used to specify some options, such as maxAge and lastModified,

A typical express. static application is as follows:

var options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders: function (res, path, stat) {  res.set('x-timestamp', Date.now()); }}app.use(express.static('public', options));

The above Code uses the public directory in the current path as a static file and sets the max-age option of the Cache-Control header to one day. For other attributes, see the express. static document.

The app. js file of the HelloExpress project created using express contains the following code:

app.use(express.static(path.join(dirname, 'public')));

In this line of code, the public directory under the HelloExpress directory is handed over to the static middleware for processing as a static file, and the corresponding http uri is "/". Path is a Node. js module, and dirname is the global variable of Node. js, pointing to the directory where the currently running js script is located. Path. join () is used to splice directories.

With the above code, you can access "localhost: 3000/stylesheets/style.css" in your browser ". Let's make some changes and change the above Code to the following:

app.use('/static', express.static(path.join(dirname, 'public')));

The above Code uses static middleware to process public directories for/static paths. Then you can access "localhost: 3000/stylesheets/" in your browser and you will see a 404 page. Change the address to "localhost: 3000/static/stylesheets/style.css.

Router

Express also provides an object called Router, which acts like a middleware. You can pass the Router directly to app. use and use the Router as you would with middleware. In addition, you can use the router to process routes such as GET and POST, or use it to add middleware. In short, you can regard the Router as a miniature version of the app.

The following code creates a Router instance:

var router = express.Router([options]);

Then you can use router like an app:

// invoked for any requests passed to this routerrouter.use(function(req, res, next) { // .. some logic here .. like any other middleware next();});// will handle any request that ends in /events// depends on where the router is "use()'d"router.get('/events', function(req, res, next) { // ..});

After defining a router, you can also pass it as a middleware to app. use:

app.use('/events', router);

The above usage applies the router to the "/events" path in the URL. All the routing policies and middleware you configure on the router object will be applied when appropriate.

Routing module

The application created by express has a routes Directory, which stores the Router module, index. js, and user. js of the application to the website. The two modules are basically the same. Let's look at index. js.

The content of index. js is as follows:

var express = require('express');var router = express.Router();/* GET home page. */router.get('/', function(req, res, next) { res.render('index', { title: 'Express' });});module.exports = router;

Index. js creates a Router instance and then calls router. get to apply the routing function to the "/" path. Finally, use module. exports to export the Router object.

The following code references index. js in app. js:

var routes = require('./routes/index');...app.use('/', routes);

First, require ('. /routes/Index') to use it as a module. This line of code imports the index. js, and the index. the router object exported by js is saved in the variable routes for later use. Note that the routes in the above Code is the router in index. js.

The second code is to use routes as a middleware and mount it to the "/" path.

Module

The previous analysis of index. js showed the usage of module. exports. Module. exports is used to export an object in the Node. js module. When the caller uses require to load the module, an instance of the exported object is obtained.

Our index. js exports the Router object. App. js uses require ('./routes/Index') to obtain a Router instance.

Module. exports has a secondary usage, that is, export using exports directly.

exports.signup = function(req, res){ //some code}exports.login = function(req, res){ //some code}

The above code (assuming it is in the users. js file) is directly exported using exports. When using exports for export, the attributes and methods you set to exports are actually module. exports. This module exports the module. exports object. You can use methods or attributes set in the form of "exports. signup". The caller can use them directly after require.

The users module code may be as follows:

var express = require('express');var app = express();...var users = require('./routes/users');app.post('/signup', users.signup);app.post('/login', users.login);...

1. What is the router path and middleware?

Enter www.baidu.com to access Baidu's homepage. the browser will automatically convert it to www.baidu.com: 80/(some parameters are omitted ). Http: // indicates that we use the http protocol to connect to the server, and www.baidu.com indicates the host address of the server, which will be resolved to an IP address by our pc through DNS. 80 is the default application layer port. /Is the path of the server we access (www.baidu.com). The server must respond to this path and take certain actions. We can regard this process as a route.

The access path '/' is the router path, and the action taken by the server is middleware, which is a special function.

2. router path

Www.baidu.com/test: path:/test

Www.baidu.com/test? Name = 1 & number = 2: the path is also/test ,? The parameters passed to the path will be understood by the server later.

3. Middleware

An Express application is essential a stack of middleware which are executed serially. (express applications are actually composed of a series of sequential execution Middleware .)

A middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application. it is commonly denoted by a variable named next. each middleware has the capacity to execute any code, make changes to the request and the reponse object, end the request-response cycle, and call the next middleware I N the stack. since middleware are execute serially, their order of execution sion is important. (middleware is actually a function that accesses the req, res, and nex parameters of express applications. This function can access any resources passed through req and res .)

If the current middleware is not ending the request-response cycle, it is important to call next () to pass on the control to the next middleware, else the request will be left hanging. (if the current middleware does not complete the res response to the web page, you can use next to leave the router to the next middleware for further execution)

With an optional mount path, middleware can be loaded at the application level or at the router level. also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system at a mount point.

Routing is generated through various HTTP methods (GET and POST). Middleware can be bound to the router path with a specific HTTP method or with all methods.

3.1 bind Middleware to all HTTP methods in the router path through the use (all) of the express application:

 app.use(function (req, res, next) {  console.log('Time: %d', Date.now());  next(); })

3.2 bind Middleware to a specific http Method in the router path through HTTP. verb of the express application:

app.get('/', function(req, res){ res.send('hello world');});app.post('/', function(req, res){ res.send('hello world');});

4. the Router object of Express

When there are more and more routes for express instances, it is best to classify routes independently, so that express instances (Apps) can better process other logical processes. Express's Router object is a simplified app instance that only has routing-related functions, including use and http verbs. Finally, the Router is mounted to the relevant path of the app through the use of the app.

 var express = require('express');var app = express();var router = express.Router();// simple logger for this router's requests// all requests to this router will first hit this middlewarerouter.use(function(req, res, next) { console.log('%s %s %s', req.method, req.url, req.path); next();});// this will only be invoked if the path ends in /barrouter.use('/bar', function(req, res, next) { // ... maybe some additional /bar logging ... next();});// always invokedrouter.use(function(req, res, next) { res.send('Hello World');});app.use('/foo', router);app.listen(3000);

The route entry of the router must be mounted to the app through app. use and app. verbs to respond. Therefore, the above Code can only be defined in the router when the app captures the route on the/foo path. Although the router has a route, but it is overwritten by the route in the app.

Appendix: Route path differences between app. verbs and app. use:

First look at a piece of test code:

var express = require('express');var app = express();var router = express.Router();app.get('/', function(req, res){   console.log('test1');});app.use('/', function(req, res){   console.log('test2');});router.get('/', function(req, res){   console.log('test3');});app.listen(4000);

Enter url: localhost: 4000

Output result: test1

Enter url: localhost: 4000/hello

Output result: test2

Conclusion: The app. get Mount '/' route only responds to GET requests exactly matching. The app. use mounts the '/' route to respond to all routes starting with '/' without limiting HTTP access. Note: Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.

The above is a detailed explanation of the code example for node. js development-express routing and middleware. For more information, see other related articles in the first PHP community!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.