Preface
Recently, Ben was experimenting with node. js and found Express.js when looking for a Web-based framework. Express.js is a relatively well-known web framework in the node. JS community, and its positioning is "minimal and flexible (concise, flexible)".
attack on the Express.js1. The underlying HTTP module
Node has an HTTP module, and in essence, we can write the Web app directly from him. The Http module is simple to use:
//////////////////App.js//////////////////load the required modulesvarHTTP = require ("http");//Create servervarApp = Http.createserver (function(Request, Response) {Response.writehead (200, { "Content-type": "Text/plain" }); Response.End ("Hello hyddd!\n");});//Start the serverApp.listen (1984, "localhost");
Run node app.js. You can see "Hello hyddd!" by visiting http://localhost:1984.
Now the problem is that the web needs to differentiate functionality through different URIs, such as:/user/profile represents user information,/about represents the site introduction ..., and the HTTP module does not directly provide dispatch functionality, of course, it is not difficult to implement it:
//////////////////App1.js//////////////////load the required modulesvarHTTP = require ("http");//Create servervarApp = Http.createserver (function(Request, response) {if(Request.url = = '/')) {Response.writehead ($, {"Content-type": "Text/plain" }); Response.End ("Home page!\n"); } Else if(Request.url = = '/about ') {Response.writehead ($, {"Content-type": "Text/plain" }); Response.End ("About page!\n"); } Else{Response.writehead (404, {"Content-type": "Text/plain" }); Response.End ("404 Not Found!\n"); }});//Start the serverApp.listen (1984, "localhost");
If you want to treat HTTP method differently, you can judge by Request.method. At this point, the Http module's short board in this scenario is clearly exposed.
2. Middle Layer: Middleware
What is middleware? According to New Wen "a short guide to Connect middleware" definition, middleware is a big lump handle requests of funcions.
As explained here, middleware is a concept, and the above connect is an HTTP Server Framework, based on the HTTP module extension, which can be said to be the predecessor of Express.js. So you can think of connect equivalence as Express.js. Let's look at a demo:
//////////////////App2.js//////////////////load the required modulesvarExpress = Require ("Express");varHTTP = require ("http");//Create servervarApp =Express ();//Add some middlewareApp.use (function(Request, response, next) {Console.log ("Step1, url:" +Request.url); Next ();}); App.use (function(Request, response, next) {Console.log ("Step2"); if(Request.url = = '/')) {Response.writehead ($, {"Content-type": "Text/plain" }); Response.End ("Main page!\n"); } next ();}); App.use (function(Request, response, next) {Console.log ("Step2:"); Console.log ("Step3"); if(Request.url = = '/about ') {Response.writehead ($, {"Content-type": "Text/plain" }); Response.End ("About page!\n"); }});//Start the serverHttp.createserver (APP). Listen (1984);
Running node app.js, accessing: Http://localhost:1984/,console The result is:
Step1, url:/
Step2
Express registers middleware,middlewares equivalent to request handlers by App.use, executes each handler in sequence when the request is processed, handler after the business is completed, By calling next (), decide whether to invoke the next handler, which is the chain processing.
Middleware is a very important feature of express.js, not one. Based on this feature, Express.js continues to implement the Routing-dispatch (allowing you to gracefully write the request handler function), public error handling (404,500 processing), providing a mechanism for developers to implement permissions validation mechanisms, and so on. In various express.js documents, the length of this piece is the longest, express.js a lot of changes and sensuality techniques will be reflected in middleware.
3.1 Top floor: Routing
App2.js, although through the middleware way, the "/" and "/about" independent, but with elegant high-readable code is not half-dime relationship. Routing is based on the middleware feature, which is actually matching different request to different handler:
//////////////////App3.js////////////////varExpress = Require ("Express");varHTTP = require ("http");varApp =Express (); App.all ("*",function(Request, response, next) {Console.log ("Step1"); Next ();}); App.get ("/",function(Request, Response) {Response.End ("Home page!");}); App.get ("/about",function(Request, Response) {Response.End ("About page!");}); App.get ("*",function(Request, Response) {Response.End ("404!");}); Http.createserver (APP). Listen (1984);
This is really a lot of elegance, and for more kinky tricks you can see a variety of documents.
3.2 Top Floor: Views
Well, Express joined the view processing mechanism and looked together:
var express = Require ("Express"); var app = Express (); // Template directory:./viewsApp.set ("views", __dirname + "/views"); // using the Jade engine app.set ("View Engine", "Jade"// addressing Views/index, submit the jade rendering and return the result function(request, Response) {Response.render ("index", {message: "I ' m Hyddd"});
Express's view mechanism is still simple.
3.3 Top level: Other "small" features
The reason I call other features "small" is that their position in the framework is secondary to the previous two (especially routing).
For a chestnut: Response,express's response is based on Http.server's response extension, which provides some new features, such as Response.Redirect ("/user/login"); and Response.sendfile ("/path/to/file");.
For others, please refer to the official documentation.
Summary
Express as described in the official website "Minimal and flexible". Express mainly solves the problem of request Routing and view templates, where middleware is the most important concept. It's a nice web frame, but this dick still has some ideas:
1. Express is not a framework for MVC because it does not have a solution for the model. Well, it's a bit of crap, because express itself is not MVC, just minimal and flexible's web framework.
2. Because express is flexible, there is no mandatory specification constraints, plus JS is the code can be written in a very casual programming language, so this dick found in the demo, Config,controller,view maintenance, management, skills can be various.
So, there is no definitive model solution (you can look for third parties, of course) and weak spec constraints, so that the whole day stepping on the shoulders of other people (giants) at the beginning of the cock do not adapt.
Resources
1. "Understanding-express"
2. "A Short Guide to Connect middleware"
3. Official document of the EXPRESSJS
Dialysis Express.js