node. JS Express 4.x Router learning experience

Source: Internet
Author: User

Express is a web framework based on the MVC pattern developed by node. JS, which is lightweight, supports MVC patterns, supports many commonly used middleware such as Body-parser: the contents of the body used to resolve client requests, Express-session:session parsing, Cookie-parser:cookie parsing), the personal feel best to put is to support routing. When we develop, we often use routing. Like in other languages, such as Java, the personal understanding of Java routing is handled by filter, or listener, and node. JS is born soon, and the ecosystem is a long way off.

The following is simply the use of Express routing.

1. Installing express NPM Install EXPRESS2, creating a routing//load Express framework
var express = require (' Express ');
Create an Express instance
var app = Express ();
Create an express routing feature that allows you to create as many routes as you need, how much you need, and how much you create.
var router = Express. Router ();

Router.use (function (req, res, next) {
Routing, similar to the Interceptor feature in Java, is handled here before the request reaches the background.
Some logic here.
req.query["name"] = "Tom";
Console.info (' Enter route, add a parameter name=tom ');
Next's role is to forward the request, this must have, if not, the request is suspended.
Next ();
});

Get ('/login ') intercepts a request for a URL containing/login in the GET request mode
Router.get ('/login ', function (req, res, next) {
Console.log (' Enter route, add a parameter age=28 ');
Req.query["age"] = "28";
Next (); Request Forwarding
});

Load the route, and place it on top of the original listening/login below.
App.get ('/login ', router);
App.get ('/login ', function (req, res) {
Console.log (' Print parameters ', req.query);
Res.end (' OK ');
});

App.listen (3000); Specify the port and start the Express Web service

Results:


3, Router.all (path, [callback ...], callback) for a route, the all method can add more than one logical method, LOGIC1,LOGIC2, the request is forwarded in order, that is, Logic1 is gone into logic2, equivalent to
Router.all (' * ', LOGIC1)
Router.all (' * ', logic2);

Example:
var express = require (' Express ');
var app = Express ();
var router = Express. Router ();

Router.use (function (req, res, next) {
req.query["name"] = "Tom";
Console.info (' Enter route, add a parameter name=tom ');
Next ();
});

Router.get ('/login ', function (req, res, next) {
Console.log (' Enter route, add a parameter age=28 ');
Req.query["age"] = "28";
Next (); Request Forwarding
});

App.get ('/login ', router);
App.get ('/login ', function (req, res) {
Console.log (' Print parameters ', req.query);
Res.end (' OK ');
});

Router.all (' * ', Logic1, Logic2);

function Logic1 (req, res, next) {
req.query["Logic1"] = "Logic1";
Next ();
}
function Logic2 (req, res, next) {
req.query["Logic2"] = "logic2";
Next ();

}

App.listen (3000); Specify the port and start the Express Web service

Results:


4. Support regular expression matching URL example:
var express = require (' Express ');
var app = Express ();
var router = Express. Router ();
Router.get (/^\/login\/result1/, function (req, res) {
Console.log (' Print parameter result1 ', req.query);
Res.end (' OK ');
})
Router.get (/^\/login\/result2/, function (req, res) {
Console.log (' Print parameter result2 ', req.query);
Res.end (' OK ');
})
App.get ('/login/* ', router);
App.listen (3000);

Test: Http://127.0.0.1:3000/login/result1?var=tom

Results


Test: Http://127.0.0.1:3000/login/result2?var=tom2

Results:


4, Router.param ([name], callback) Http://127.0.0.1:3000/user/:id mode, Router object's Param method for path parameter processing

var express = require (' Express ');
var app = Express ();
var router = Express. Router ();
Router.param (' id ', function (req, res, next, id) {
Console.log (' Print id1 ' +id);
Next ();
})

Router.get ('/user/:id ', function (req, res, next) {
Console.log (' Print Id2 ' +req.params.id);
Next ();
});

Router.get ('/user/:id ', function (req, res) {
Console.log (' Print id3 ' +req.params.id);
Res.end ();
});
App.get ('/* ', router);
App.listen (3000);

Test: Http://127.0.0.1:3000/user/tom

Results


5. Router.route (path) Route handles HTTP requests such as Get put post delete in a chained way

var express = require (' Express ');
var app = Express ();
var router = Express. Router ();

Router.param (' user_id ', function (req, res, next, id) {
Sample user, would actually fetch from DB, etc ...
Req.user = {
Id:id,
Name: ' TJ '
};
Next ();
});

Router.route ('/users/:user_id ')
. All (function (req, res, next) {
Runs for all HTTP verbs first
Think of it as route specific middleware!
Next ();
})
. Get (function (req, res, next) {
Res.json (Req.user);
})
. put (function (req, res, next) {
Just an example of maybe updating the user
Req.user.name = Req.params.name;
Save User ... etc
Res.json (Req.user);
})
. Post (function (req, res, next) {
Next (new Error (' not implemented '));
})
. Delete (function (req, res, next) {
Next (new Error (' not implemented '));

})

This is all and will be complemented by further refinement.

node. JS Express 4.x Router learning experience

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.