node. JS Framework Express

Source: Internet
Author: User

Express is on the basis of node. JS, the development of a concise and practical framework structure, the use of this thing, we can more easily handle a lot of things. Just get started, it's a Beethoven!

There are several ways to install Express in general.

First, use NPM installation, cmd input NPM install EXPRESS-G, this-G is a global installation, that is installed in the folder you use "config set global" settings, it should be noted that after installation, You need to change the environment variable and its path to point to your installation directory.

Second, copy and paste. (...... Nonsense! However, there is a security issue, as there may be data loss in the process of copying and pasting.

Finally, it's worth noting that once you have a folder inside your Nodejs that has an express frame, and he's been quoted by you, then no matter how you save it, it's useless ... Either remove it or overwrite it.

Express ()

Create an express app

The equivalent of a new object, but also can write less three letters, the express into the variable app, from the app to become the owner!

1 2 3 4 5 6 7 var express = require( ‘express‘   ); var app = express(); app.get( ‘/‘ , function (req, res){      res.send( ‘hello world‘ ); });   app.listen(3000);

App.set (name, value)

Set the value of the setting item name to value

This method is mainly used to set the port, or set folder storage, other uses seem to be relatively rare

0 S app.set( ‘title‘ , ‘My Site‘ ); app.get( ‘title‘ ); // => "My Site"

App.get (name)

Gets the value of the set item name

0 S 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.

1 2 app.enable( ‘trust proxy‘ ); app.get( ‘trust proxy‘ ); // => true

App.disable (name)

Set the value of the setting item name to False.

1 2 app.disable( ‘trust proxy‘ ); app.get( ‘trust proxy‘ ); // => false

app.enabled (name)

Check whether the settings item name is enabled

1 2 app.enabled( ‘trust proxy‘ ); // => falseapp.enable(‘trust proxy‘); app.enabled( ‘trust proxy‘ ); // => true

app.disabled (name)

Check whether the settings item name is disabled

1 2 app.disabled( ‘trust proxy‘ ); // => trueapp.enable(‘trust proxy‘) app.disabled( ‘trust proxy‘ ); // => false

App.use ([path], function)

Here is a practical scenario where a common application is to use the./public to provide a static file service with the express.static () middleware:

Here path is using the default "/", express.static () Save the file name of the resource storage, __dirname is the specified global variable, indicating during development, the line of code in the directory (in fact, the equivalent of the current folder)

1 2 3 4 // GET /javascripts/jquery.js // GET /style.css // GET /favicon.ico app.use(express. static (__dirname + ‘/public‘ ));

If you want to prefix all the static file paths with "/static", you can use the "Mount" feature. If the Req.url does not contain this prefix, the mounted middleware will not execute. When function is executed, this parameter is not passed. This only affects this function, and the Req.url in the later middleware will contain "/static"

1 2 3 4 // GET /static/javascripts/jquery.js // GET /static/style.css // GET /static/favicon.ico app.use( ‘/static‘ , express. static (__dirname + ‘/public‘ ));

The order of the middleware defined using App.use () is very important, they will be executed sequentially, and the order of use determines the priority of the middleware. For example, usually Express.logger () is the first component to use, recording each request

1 2 3) 4 5 app.use(express.logger()); app.use(express. static (__dirname + ‘/public‘ )); app.use( function (req, res){    res.send( ‘Hello‘ ); });

If you want to ignore the record of requesting a static file, but for the route and middleware defined after logger () want to continue to record, simply move the static () to the front of the line:

1 2 3) 4 5 app.use(express. static (__dirname + ‘/public‘ )); app.use(express.logger()); app.use( function (req, res){    res.send( ‘Hello‘ ); });

Another realistic example is the possibility of providing static file services from multiple directories, with the following example taking precedence from the "./public" Directory

1 2 3 app.use(express. static (__dirname + ‘/public‘ )); app.use(express. static (__dirname + ‘/files‘ )); app.use(express. static (__dirname + ‘/uploads‘ ));

App.engine (ext, callback)

The template engine that registers the template engine's callback to handle the EXT extension by default, according to the file name extension require (). For example, if you want to render a "foo.jade" file, Express will execute the following code internally, and then cache require (), which will improve the performance of later operations

1 app.engine( ‘jade‘ , require( ‘jade‘ ).__express);

Those that do not offer. __express or if you want to render a file with an extension that is inconsistent with the default of the template engine, you can also use this method. For example, you want to use the Ejs template engine to process ". html" suffix files:

1 app.engine( ‘html‘ , require( ‘ejs‘ ).renderFile);

In this example Ejs provides a. RenderFile () method and express the expected format: (Path, options, callback) consistent, you can internally give this method an alias ejs.__express, so you can use the ". Ejs "Extension without any changes required

Some template engines do not follow this conversion, and there is a small project consolidate.js specifically wrapping all of the node's popular template engines so that they look the same inside Express.

1 2 3 var engines = require( ‘consolidate‘ ); app.engine( ‘haml‘ , engines.haml); app.engine( ‘html‘ , engines.hogan);

App.param ([name], callback)

The processing logic for the routing parameters. For example, when the user appears in a routing path, you may automatically load the logic of the loading users and put it in the req.user, or verify that the input parameters are correct.

The following code snippet shows that callback is much like a middleware, but adds a value to the parameter, named ID. It tries to load the user information and assigns it to req.user, otherwise it passes the error next (ERR).

1 2 3 4 5 6 7 8 9 10 11 12 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( new Error( ‘failed to load user‘ ));              }      }); });

You can also just pass a callback, so you have a chance to change the App.param () API. For example, Express-params defines the following callback, which allows you to use a given regular to constrain parameters.

The following example is a little bit more advanced, checking if the second parameter is a regular, returning a callback function that behaves like the "user" parameter example above.

1 2 3 4 5 6 7 8 9 10 11 12 13 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.listen ()

Listen for requests on the given host and port, this and node's document HTTP. Server#listen () is the same

1 2 var express = require( ‘express‘ ); var app = express(); app.listen(3000);

The app returned by Express () is actually a javascriptfunction, which is designed to be passed to node's HTTP servers as a callback function for processing requests. Because the app is not inherited from HTTP or HTTPS, it's just a simple callback function that allows you to handle both HTTP and HTTPS versions of the service with the same code.

1 2 3) 4 5 var express = require( ‘express‘ ); var https = require( ‘https‘ ); var http = require( ‘http‘ ); var app = express();http.createServer(app).listen(80); https.createServer(options, app).listen(443);

The App.listen () method is just a quick method, if you want to use HTTPS, or both HTTP and HTTPS, you can use the code above

1 2 3 4 app.listen = function (){      var server = http.createServer( this );      return server.listen.apply(server, arguments); };


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.