Express. JS Usage Details _ node. js

Source: Internet
Author: User
Express is a simple and flexible node. js Web application framework. It provides a series of powerful features to help you create various Web applications. Next, we will analyze it step by step. Do not leave node installation (download) and create a directory on your machine to start your first application.

$ mkdir hello-world

In this directory, you will define the application "package", which is no different from any other node package. The json file in the file directory clearly defines a dependency. You can use the npm command to get the latest version of express. You like to do this, instead of installing versions other than "3. x" to prevent any unknown surprises.

{ "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": {  "express": "3.x"}}

Now you have a package. You can use npm (1) to install the json file in this directory. In this case, you only need to enter:

$ npm install

Once npm is complete, you will have a dependency on Express 3.xin the/node_modules directory. You can use npm ls to verify this, as shown in the following code snippet.

$ npm lshello-world@0.0.1 /private/tmp└─┬ express@3.0.0beta7 ├── commander@0.6.1 ├─┬ connect@2.3.9 │ ├── bytes@0.1.0 │ ├── cookie@0.0.4 │ ├── crc@0.2.0 │ ├── formidable@1.0.11 │ └── qs@0.4.2 ├── cookie@0.0.3 ├── debug@0.7.0 ├── fresh@0.1.0 ├── methods@0.0.1 ├── mkdirp@0.3.3 ├── range-parser@0.0.4 ├─┬ response-send@0.0.1 │ └── crc@0.2.0 └─┬ send@0.0.3  └── mime@1.2.6

Now create the application itself! Create a file named app. js or server. js, whatever you like, introduce express, and then create a new application with express:

var express = require('express');var app = express();

The new application instance can start to define the route through app. VERB (). In this case, the "GET/" request is responded through the "Hello World" string. Req and res are completely identical node objects provided to you, so you may call res. pipe (), req. on ('data', callback) and other things you will do that have nothing to do with Express.

Express enhances these objects to provide you with high-level interfaces such as res. send (), in addition to adding content length for you:

app.get('/hello.txt', function(req, res){ res.send('Hello World');});

Now, you can call the app. listen () method for the connection to bind and listen, and accept the same parameters as the net. Server # listen () of the node ():

var server = app.listen(3000, function() {  console.log('Listening on port %d', server.address().port);});

Use express (1) to generate an application

The Express Team maintains a convenient project builder named express-generator (1 ). If you use npm to globally install express-generator, you can access it from anywhere on your computer:

$ npm install -g express-generator

This tool provides a simple way to get an application framework, but the scope is limited. For example, it only supports several template engines, express itself supports creating any website framework template for node. You can use help to view the following information:

Usage: express [options]Options: -h, --help     output usage information -V, --version    output the version number -e, --ejs      add ejs engine support (defaults to jade) -H, --hogan     add hogan.js engine support -c, --css  add stylesheet support (less|stylus|compass) (defaults to plain css) -f, --force     force on non-empty directory

If you want to generate an application that is supported in any situation, simply execute ::

$ express --css stylus myappcreate : myappcreate : myapp/package.jsoncreate : myapp/app.jscreate : myapp/publiccreate : myapp/public/javascriptscreate : myapp/public/imagescreate : myapp/public/stylesheetscreate : myapp/public/stylesheets/style.stylcreate : myapp/routescreate : myapp/routes/index.jscreate : myapp/viewscreate : myapp/views/index.jadecreate : myapp/views/layout.jadeinstall dependencies:$ cd myapp && npm installrun the app:$ DEBUG=myapp node app

For any node application, you must install the following dependencies:

Let's get started.

$ npm start

This is all you need to make a simple application start and run. Remember, Express is not bound to any specific directory structure. This is just a guide. You can view the example in the github repository for selection of the application structure.

Error Handling

The definition of error handling middleware is like that of common middleware. However, the number of four parameters must be defined. This is the function signature (err, req, res, next ):

app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!');});

Although the mandatory error handling middleware is generally not defined at the end, after other apps. use (), the call is as follows:

var bodyParser = require('body-parser');var methodOverride = require('method-override');app.use(bodyParser());app.use(methodOverride());app.use(app.router);app.use(function(err, req, res, next){ // logic});

The responses from these middleware are completely arbitrary. You may want to respond to an HTML error page, a simple message, a JSON string, or any other response you like.

To build an organized and high-level framework, you can define several of these error handling middleware, just as you would define common middleware. For example, if you want to define an error processor for XHR requests, you may do the following:

var bodyParser = require('body-parser');var methodOverride = require('method-override'); app.use(bodyParser());app.use(methodOverride());app.use(app.router);app.use(logErrors);app.use(clientErrorHandler);app.use(errorHandler);

In more general logErrors, you can write request and error messages to stderr, logugly, or similar services:

function logErrors(err, req, res, next) { console.error(err.stack); next(err);}

ClientErrorHandler is defined as follows. Note that this error will be passed explicitly to the next one.

function clientErrorHandler(err, req, res, next) { if (req.xhr) {  res.send(500, { error: 'Something blew up!' }); } else {  next(err); }}

The following errorHandler comprehensive implementation can be defined:

function errorHandler(err, req, res, next) { res.status(500); res.render('error', { error: err });}

Online User count

This section describes in detail a (small) application that uses Redis to track the number of online users. First, create a package. The json file contains two attachments, one for the redis client and the other for the Express itself. Make sure that you have packaged redis and run it through $ redis-server.

{ "name": "app", "version": "0.0.1", "dependencies": {  "express": "3.x",  "redis": "*" }}

Next, you need to create an application and connect to redis:

var express = require('express');var redis = require('redis');var db = redis.createClient();var app = express();

The next middleware tracks online users. Here we will use the sorting set, so that we can query online users through redis, it only takes N milliseconds. We use timestamps as the member's "Online Standard ". Note: here we use the user-agent string to replace the common user ID.

app.use(function(req, res, next){ var ua = req.headers['user-agent']; db.zadd('online', Date.now(), ua, next);});

The next middleware uses zrevrangebyscore at the last moment to obtain the maximum number of online users. We always get the most recent online users, whose upper limit is the current timestamp minus 60000 milliseconds.

app.use(function(req, res, next){ var min = 60 * 1000; var ago = Date.now() - min; db.zrevrangebyscore('online', '+inf', ago, function(err, users){  if (err) return next(err);  req.online = users;  next(); });});

Finally, we use a url and bind it to a port! When you access this application in a new browser, you will see an increase in the number of online users.

app.get('/', function(req, res){ res.send(req.online.length + ' users online');});app.listen(3000);

Reverse Proxy of Expree

Using Expree behind the reverse proxy, such as Varnish or Nginx is insignificant, but it needs to be configured. Enable "Trust proxy" to set the app. enable ("trust proxy"), Express has some reverse proxy skills. The X-Forwarded-* header fields may be trusted, otherwise they may be easily spoofed.

Enabling this setting has some subtle effects. The first one is that X-Forwarded-Proto may be set by the reverse proxy, telling the app that it is https or just a simple http. This value is reflected by req. protocol.

The second change is that the req. ip and req. ips values are filled in the X-Forwarded-For address list.

Debug Express

Express uses the debugging module to record Path Matching and application mode information. To see this information, simply set the debugging environment variable to express: *. After the application is started, you will view the debugging information on the console.

$ DEBUG=express:* node ./bin/www

Running this hello world example will print the following content:

express:application booting in development mode +0msexpress:router defined get /hello.txt +0msexpress:router defined get /hello.txt +1ms

In addition, the debugging module is also used for programs that express executable (generator) generation. The default scope is my-application debug namespace.

You can use the following command to enable these debugging statements:

$ DEBUG=my-application node ./bin/www

For more information about debugging, see the debugging guide.

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.