transferred from: http://www.cnblogs.com/ae6623/p/4433048.html
This is the first article in the Express 4.x API translation series. As the author recently in learning Nodejs, just touched the node-style development model, by the asynchronous IO programming way deeply attracted, so prepare the system to learn this new technology. Because there is no basis for any nodejs, and do not know where to learn from, before also studied Byvoid's "Nodejs Development Guide" also do not know that is not an introduction. Want to try to write a sample of the micro-blog inside, but found that their installed Express is the latest 4.X, online for express content is very small, not to mention the latest development documents, simply began to translate the Express API, this is Express 4. X the first article of the Chinese Manual, the following content from the original website >>>express official website
Write in front
The express version for this article is V4.0.0, and the content is not guaranteed to apply to the previous version. Since the author belongs to just contact Express so did not study the difference between the previous version and the 4.0.0 version, then in the next time, the author will translate more articles about Express for everyone to learn.
Express ()
Create an express app
var express = require (' Express '); var app = Express (); App.get ('/', function (req,res) { res.send (' Hello World ');}); App.listen (3000);
setting
The following setting options will show you how to change the behavior of Express:
- ENV runtime Environment, default to Process.env.NODE_ENV (node_env environment variable) or "development";
- Trust proxy activates the reverse proxy mode, which is not activated by default;
- JSONP Callback name JSON callback function substitution body, default is empty;
- Case sensitive routing is used to activate the route casing sensitivity, the default is not activated, "/foo" and "/foo" are treated the same;
- Strict routing activates strict routing mode, the default "/foo" and "/foo/" are treated the same;
- The view cache activates the template engine compilation cache, which is enabled by default in production mode;
- Default template engine in view engine default state
- Views template directory address, default to "PROCESS.CWD () + '/views '"
App.set (Name,value)
Set the value of the set item name to value
App.set (' title ', My Site); App.get (' title ');//=> "My site"
app.get (name)
Gets the value of the set item name
App.get (' title ');//=> Undefinedapp.set (' title ', ' My Site '); App.get (' title ');//=> "My site"
app.enable (name)
Set the value of the setting item name to True
App.enable (' trust proxy '); App.get (' trust proxy ');//=>true
app.disable (name)
Set the value of the set item name to False
App.disable (' trust proxy '); App.get (' trust proxy ');//=>false
app.enabled (name)
Checks whether the state of the set item name is active
app.enabled (' trust proxy ');//=>falseapp.enable (' trust proxy '); app.enabled (' trust proxy ');//=>true
app.disabled (name)
Checks whether the state of the setting item name is inactive
app.disabled (' trust proxy ');//=>trueapp.disable (' trust proxy '); app.disabled (' trust proxy ');//=>false
App.use ([path],function)
With the given middleware function, the optional parameter path, which defaults to "/".
var express = require (' Express '); var app = Express (); Simple Loggerapp.use (function (req,res,next) { console.log ("%s%s", Req.method,req.url); Next ();}); App.use (function (req,res,next) { res.send (' Hello World ');}); App.listen (3000);
Now the "mount" path is stripped and is not visible to the middleware, that is, the mounted path will not appear on the Req Road, the middleware function callback parameter req can not find the path. This is designed so that the middleware can execute at any prefix without having to change any code. Here's a concrete example of using "./public" to manage static files, using "express.static ()" Middleware
Get/javascript/jquery.js//get/style.css//get/favicon.icoapp.use (express.static (__dirname + '/public '));
For example, if you want to add the prefix "/static" for all static files, you can use the "mount" function to support the operation. The mounted middleware function is not called unless the prefix is included in the Req.url and is stripped when the function is called. Of course, this only affects this function, and later middleware will see that the "/static" in Req.url is included, unless the middleware is also mounted under "/static".
Get/static/javascripts/jquery.js//get/static/style.css//get/static/favicon.icoapp.use ('/static ', Express.static (__dirname + '/public '));
The order of the "defined" app.use () is very important, and they are called sequentially, so the order in which the App.use () is called determines the priority of the middleware. For example, any logging middleware will typically be defined before any middleware being used:
var logger = require (' Morgan '); App.use (Logger ()), App.use (express.static (__dirname + '/public ')), App.use (function (req,res) { res.send (' Hello ') );});
Now if you want to ignore the request for static file records, but want to continue to record logger () after the definition of the routing and middleware, then you just need to move the static () to logger ().
App.use (express.static (__dirname + '/public ')), App.use (Logger ()), App.use (function (req,res) { res.send (' Hello ') );});
Another example is that you might use multiple folders to provide static file services, and the following example will take precedence from the "/public" folder to select static files.
App.use (express.static (__dirname + '/public ')) App.use (express.static (__dirname + '/files ')); App.use ( Express.static (__dirname + ' uploads '));
app.engine (ext,callback)
Registering the template engine's callback to handle files with the extension ext will, by default, introduce the appropriate template engine based on the file's extension. For example, if you attempt to render a "foo.jade" file, Express will invoke the following code internally, and cache require () to improve the performance of subsequent calls.
App.engine (' Jade ', require (' Jade '). __express);
If the template engine you are using does not provide the. __express out of the box-or if you want to "map" a different extension for the template engine, you can use this method. For example, mapping the Ejs template engine to render ". html" files
App.engine (' HTML ', require (' Ejs '). RenderFile);
In this example, Ejs provides a. RenderFile () method and express expected format: (path,options,callback) Consistent, note that this allows you to have an alias for ejs.__express internally, so you can continue to use the " . ejs "Extension without needing to do anything extra.
Some template engines do not follow this conversion convention, there is a small project consolidate.js all of the node's popular template engines are packaged so that they look the same within Express.
var engines = require (' consolidate '); App.engine (' Haml ', Engines.haml); App.engine (' html ', Engines.hogan);
App.param ([name],callback)Map route parameter processing rules, such as when: User appears in a routing path, you may need to automatically load the user logic into Req.user, or verify that the input parameters are correct. The callback shown in the following code fragment is much like a middleware, so it supports asynchronous operations, but adds an additional parameter, named ID, which attempts to load user information and assigns it to req.user, otherwise passes an error to next (err).
App.param (' User ', function (req,res,next,id) { user.find (id,function (err,user) { if (err) { next (err) } else if (user) { req.user = user; Next (); } else { Next (' Failed to load user ');});} ) ;
Or you just pass a callback function, in which case you will have the opportunity to change the API of App.param (), for example Express-params defines the following callback condition, allowing you to restrict a given parameter through a regular expression.
This example is somewhat advanced when it detects that if the second argument is a regular expression, it returns a callback function that resembles the behavior of the "user" example above
App.param (function (NAME,FN) { if (fn instanceof RegExp) { return function (req,res,next,val) { var captures ; if (captures = Fn.exec (String (val))) { Req.params[name] = captures; Next (); } else{ Next (' Route ');}}} );
This function can now be used to validate parameters very efficiently, or to provide a grouping after a regular capture.
App.param (' id ',/^\d+$/); App.get ('/user/:id ', function (req,res) { res.send (' user ' + req.params.id);}); App.apram (' Range ',/^ (\w+) \.\. ( \w+)? $/); App.get ('/range/:range ', function (req,res) { var range = Req.param.range; Res.send (' from ' + range[1] + ' to ' + range[2]);
app. VERB (Path,[callback...],callback)
App. The VERB () method provides a routing method for Express, where VERB refers to an HTTP action, such as App.post (). can provide multiple callback, these callback will be treated equally, they behave like middleware, but there is an exception, if a callback call next (' Route '), then the callback behind him will be ignored. This situation will be applied when a route prefix is satisfied, but it is not necessary to use this callback function to process the route, so it is passed backwards.
The following code snippet demonstrates one of the simplest route definitions. Express will then convert the string expression to a regular expression, and then internally match the passed-in expression. Request parameters will not be taken into account. For example, "Get/" will match the following routing rules, and the same "get/?name=tobi" will be matched by the following rules.
App.get ('/', function (req,res) { res.send (' Hello World ');});
Regular expressions can also be used, especially if you have special restrictions that will be useful, such as the following example will match "get/commits/71dbb9c" and will also match "get/commits/71dbb9c." 4c084f9″.
App.get (/^\/commits\/(\w+) (?: \.. \.. (\w+))? $/,function (req,res) { var from = req.params[0]; var to = req.params[1] | | ' HEAD '; Res.send (' Commit range ' + from + ' ... ' + to);});
Some callbacks can be passed, which is useful for reusing some load resources and verifying the middleware.
App.get ('/user/:id ', user.load,function () { //...});
If you have a lot of middleware for a routing rule, you can also use the route AP's All ().
var middleware = [Loadforum,loadthread]; App.route ('/forum/:fid/thread/:tid ') . All (Loadforum). All ( loadthread) . Get (function () {//...}) . Post (function () {//...})
All middleware rules will be applied with get and POST requests.
App.all (path,[callback...],callback)This method function is like an app. VERB () method, but the difference is that he matches all of the HTTP actions. This method is useful for mapping "global" to a logical map of a particular path, or for arbitrary mapping. For example, if you want to place the following route definition before all other route definitions, this will cause all requests from this rule to require authentication and automatically load a user. Keep in mind that all callback functions should not be treated as endpoints, Loaduser can be considered as a task and then go to call next () to continue to match the subsequent routing rules.
App.all (' * ', requireauthentication,loaduser);
It is equivalent to:
App.all (' * ', requireauthentication); App.all (' * ', loaduser);
Another better example is the global whitelist function, which is much like the previous one, but it restricts the prefix to "/API":
App.all ('/api/* ', requireauthentication);
app.route (path)
Returns an instance of a route that can then be used to handle HTTP actions using selectable middleware. Using App.route () is a recommended way to avoid repeating named routing rules and the resulting errors.
var app = Express (); App.route ('/events ') . All (function (req,res,next) { //runs-all HTTP verbs first //think of it as Route Specific middleware! }) . Get (function (req,res,next) { Res.json (...); }) . Post (function (req,res,next) { //maybe add a new event ...});
app.locals
The local variables of the application are appended to all the templates that are rendered within the application. This is a very useful template function, just like an application-level data.
App.locals.title = "My App"; app.locals.strftime = require (' strftime '); app.locals.emall = ' [email protected] ';
The App.locals object is a JavaScript object. The attributes added to it will be exposed as local variables in the application.
App.locals.title//=> ' My App ' app.locals.email//= ' [email protected] '
By default, Express has an application-level local variable, which is setting.
App.set (' title ', ' My App ');//use settings.title in a view
App.render (view,[options],callback)
The render view,callback is used to process the returned string after rendering. This is the application-level version of Res.render (), and they behave the same.
App.render (' email ', function (err,html) { //...}); App.render (' email ', {name: ' Tobi '},function (err,html) { //...})
App.listen ()
Listen for requests on the given host and port, this and node's document HTTP. Server#listen () is the same
var express = require (' Express '); var app = Express (); App.listen (3000);
The app returned via Express () is in fact a JavaScript function designed to be passed to node's HTTP server as a callback function for processing requests. Since the app is not inherited by HTTP or HTTPS, it's just a simple callback, so this allows you to easily use the same generation to handle HTTP and HTTPS requests.
var express = require (' Express '); var https = require (' https '); var http = require (' http '); var app = Express (); Http.createserver (APP). Listen, Https.createserver (Options,app). Listen (443);
The App.listen () method is simply defined as an easy way to use the above technique if you want to use the HTTPS protocol or both HTTP and HTTPS.
App.listen = function () { var server = Http.createserver (this); Return server.listen.apply (server,arguments);}
Transferred from: http://www.90it.net/expressjs-4-api-zh-cn-application.html
Nodejs Express 4.X Chinese API 1---Application