We've written the HelloWorld example based on Express, and we've created a helloexpress project with the Express Generator tool, but some of the code hasn't been properly explained because they involve concepts such as routing and middleware, Words is not clear, so I specialize in an article about routing and middleware. Routing
The usual format for HTTP URLs is this:
http://host[:p Ort][path]
HTTP represents the protocol.
Host represents the hosts.
Port is an optional field and the default is 80 when not provided.
path Specifies the URI of the requested resource (uniform Resource Identifier, the Uniform Resource Locator), which, if not given a path in the URL, will typically default to "/" (usually by a browser or other HTTP client completion supplement).
The so-called routing is how to handle the path part in an HTTP request. such as "http://xxx.com/users/profile" This URL, the route will determine how to deal with/users/profile this path.
To review the express version of the HelloWorld code that we provided in the 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 are listening at Port 8000 ');
};
The App.get () call in the above code actually adds a route to our web site, specifying that the "/" path is handled by the function represented by the second parameter of get.
Express objects can specify routes for common HTTP methods, using the following methods:
App. Method (Path, callback [, callback ...])
Method can be lowercase for HTTP methods such as GET, post, and so on, such as App.get,app.post. The path section can be either a literal or regular expression of a string. In the simplest case, a parameter of the App.get () call in the preceding code is changed to ' * ', meaning is different. Before the change, only access to "http://localhost:8000" or "http://localhost:8000/" in this form of access will return "Hello world!", and then change, like "http://localhost : 8000/xxx/yyyy.zz "This access will also return" Hello world! ".
When using Express to build a Web server, it is important to decide how to respond to a request for a path, or to route a process.
The most direct route configuration method is to invoke App.get (), App.post () a piece of configuration, but for the site that needs to deal with a large number of routes, this will be fatal. So, we need to combine routing parameters (query string, regular expression, custom parameters, post parameters) in our actual development to reduce the amount of work to improve maintainability. For more detailed information, refer to http://expressjs.com/guide/routing.html. Middleware
There is a middleware (middleware) concept in Express. Middleware is the function that executes at this stage before the request is received and the response is sent.
To insert a middleware into a routed processing chain, you can use the Express object's using method. The prototype of the method is as follows:
App.use ([path,] function [, function ...])
When App.use does not supply the path parameter, the path defaults to "/". When you install middleware for a path, the middleware is applied when a path based on that path is accessed. For example, if you set up middleware for "/ABCD", then "/abcd/xxx" is also applied to the middleware when it 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 function to drive the middleware call chain Next, if you want the following middleware to continue processing the request, you need to call the next method.
A typical call to apply a middleware function to a path is this:
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 handle a GET request for a static file in a Web site that can be accessed via express.static.
The use of express.static is as follows:
Express.static (root, [options])
The first argument, root, is the root of the static resource to be processed, either an absolute or a relative path. The Second optional parameter is used to specify some options, such as MaxAge, lastmodified, etc., and more options are presented here: http://expressjs.com/guide/using-middleware.html#middleware.built-in.
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 takes the public directory under the current path as a static file, and the Max-age option for the Cache-control header is 1 days. There are other properties that you can use against Express.static's documentation.
There is one line of code in the App.js file for the Helloexpress project created using Express:
App.use (Express.static (Path.join (__dirname, ' public '));
This line of code gives the public directory in the Helloexpress directory as a static file to the static middleware for processing, and the corresponding HTTP URI is "/". Path is a node.js module, __dirname is a node.js global variable that points to the directory where the currently running JS script resides. Path.join () is used to splice catalogs.
With the above code, you can access "HTTP://LOCALHOST:3000/STYLESHEETS/STYLE.CSS" in the browser. Let's make a little change and change the above code to the following:
App.use ('/static ', Express.static (Path.join (__dirname, ' public '));
In the code above, the static middleware is used to process the public directory for the/static path. Then you use the browser to visit the "http://localhost:3000/stylesheets/" will see a 404 page, the address replaced by "http://localhost:3000/static/stylesheets/style.css" on it. Router
Express also provides an object called router, which behaves much like a middleware, and you can pass router directly to App.use, using router as a middleware. You can also use router to process routes for GET, post, and so on, and you can use it to add middleware, but you can look at 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 (code from Http://expressjs.com/4x/api.html#router) as you would with the app:
Invoked for no requests passed to this router
router.use (function (req, res, next) {
//... some logic here ... l Ike any other middleware
next ();
};
Would handle any request this ends In/events
//depends on where the router was "use" () ' d '
router.get ('/events '), Function (req, res, next) {
//..
});
Once the router is defined, it can also be passed to App.use as a middleware:
App.use ('/events ', router);
The above usage will apply router to the "/events" path in the URL, and the various routing strategies and middleware you configure on the router object will be applied at the right time. Routing Module
The Express tool creates an application that has a routes directory, which is saved under the router module, index.js and User.js, which are applied to the site. These two modules are basically the same, let's look at index.js.
Here's what the Index.js:
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 the routing function is applied to the "/" path. Finally, use Module.exports to export the router object.
The following is the code referenced to Index.js in App.js:
var routes = require ('./routes/index ');
...
App.use ('/', routes);
In the first place, require ('./routes/index ') uses it as a module, which imports the Index.js and stores the Index.js exported router object in the variable routes for subsequent use. Notice that the routes in the code above is the router in index.js.
The second code, which takes routes as a middleware, is mounted on the "/" path. Module
The use of Module.exports is seen in the previous analysis of Index.js. Module.exports is used to export an object within a Node.js module, and the caller obtains an instance of the exported object when the module is loaded with require.
Our Index.js exports the router object. App.js uses require ('./routes/index ') to obtain a router instance.
Module.exports also has an auxiliary usage, which is to export directly using exports.
Exports.signup = function (req, res) {
//some code
}
exports.login = function (req, res) {
//some code
}
The above code (assumed to be in the Users.js file) is exported directly using exports. When you use exports to export, the properties and methods that you set to exports are actually module.exports. This module ultimately exports the Module.exports object, and you use a method or property set like "Exports.signup", which the caller can use directly after require.
The code for using the Users module might be this:
var express = require (' Express ');
var app = Express ();
...
var users = require ('./routes/users ');
App.post ('/signup ', users.signup);
App.post ('/login ', users.login);
...
helloexpress and looking back
Well, with the previous introduction, look at the application structure and code of Express generation, the problem is not big. Now let's summarize the helloexpress application. directory Structure
Express will create an application according to a specific directory structure. Bin directory, which is a www file, in fact, is a JS script file, using NPM start to launch the site will call www. You can see the console output to confirm. The public directory, which contains a number of static files, the default generated items, only stylesheets under a style.css file. JavaScripts subdirectory can be placed JS file, images subdirectory playback picture. The routes directory is placed in the routing module, the previous analysis. You can configure your site's routing here. An HTML template file that is placed in the views directory. We'll talk about it next time. The Node_modules directory is based on Package.json generated, Package.json by Express generation App.js, application portal app.js
App.js's code is as follows, and then review:
var express = require (' Express ');
var path = require (' path ');
var favicon = require (' Serve-favicon ');
var logger = require (' Morgan ');
var cookieparser = require (' Cookie-parser ');
var bodyparser = require (' Body-parser ');
var routes = require ('./routes/index ');
var users = require ('./routes/users ');
var app = Express ();
View engine Setup App.set ("Views", Path.join (__dirname, ' views '));
App.set (' View engine ', ' Jade ');
Uncomment after the placing your Favicon in/public//app.use (Favicon (path.join, ' public ', ' __dirname '));
App.use (Logger (' dev '));
App.use (Bodyparser.json ());
App.use (bodyparser.urlencoded ({extended:false}));
App.use (Cookieparser ());
App.use (Express.static (Path.join (__dirname, ' public '));
App.use ('/', routes);
App.use ('/users ', users);
Catch 404 and forward to the error handler App.use (function (req, res, next) {var err = new error (' Not Found ');
Err.status = 404;
Next (ERR);
}); Error handlers//Development error handler//would print StacktRace if (App.get (' env ') = = ' development ') {App.use (function (err, req, res, next) {Res.status (Err.status | | 500);
Res.render (' error ', {message:err.message, error:err});
}); }//Production error handler//No stacktraces leaked to user app.use (function (err, req, res, next) {Res.status (ERR.S Tatus | |
500);
Res.render (' error ', {message:err.message, error: {}});
});
Module.exports = app;
Now look at the code above, there should be no pressure. Only one place, the configuration template engine two lines of code, behind the mysterious story, the next time we say.
Other articles: Node.js Development Primer--express Installation and use Node.js Development portal--http File Server node.js Development entry--helloworld re-analysis Node.js Development Introduction--environment construction and HelloWorld