Get started with Express (node. JS Web application Framework)

Source: Internet
Author: User

Use Express framework to build simple NODEJS applications

Start

After confirming that Nodejs is installed (NPM will also be installed after the latest node is installed), NPM can be understood as a toolkit for NODEJS. You can check the version to see if the installation was successful:

F:\>node-vv0. 10.32f:\>npm-v1.4.28

Create a directory in which the application "package" file is defined first, and it is the same as the other node packages. That is to create a Package.json file in this directory, in which express as a dependency. You can also use npm info express version it to get the latest version number of the Express, preferably using the latest version number instead of the 3.x below, so the new features won't make you feel strange.

f:\>NPM Info Express versi4.9.5f:\>mkdir Hellonode

Manually create an application-dependent package file Package.json:

{  "name": "Hello-world",  "description": "Hello World Test App",  "version": " 0.0.1 ",  true,  " dependencies ": {    " Express ":" 3.x "   }
"Scripts": {
"Start": "Forever App.js",
"Test": "Supervisor App.js"
}
}

Package.json file is very important, at least I think, the dependencies field specifies that the program depends on the package, as long as it is specified here, NPM install automatically installs all the packages specified in this. Scripts fields are also more commonly used, such as above, if you start the program, you can use the "npm start" or "NPM Test" command, specify that supervisor can automatically detect program changes.

After the Package.json file is ready, run the NPM Install command, the dependent packages specified in the file are installed,

F:\>CD Hellonode &&npm Install[email protected]3.17.6Node_modules\express├──basic[Email protected]├──merge[Email protected]├──[email protected]0.2.4├──escape[Email protected]├──[email protected]0.1.2├──range[Email protected]├──cookie[Email protected]├──[email protected]1.0.0├──media[Email protected]├──[email protected]1.3.0├──[email protected]1.1.0├──[email protected]0.4.5├──[email protected]3.0.0├──[email protected]0.5.0 ([email protected]) ├──[email protected]2.0.0 ([email protected]) ├──[email protected]1.3.2 ([email protected]) ├──proxy[Email protected] ([email protected], [email protected]) ├──[email protected]0.9.3 ([email protected], [email protected], [email protected], [email protected], on-finished@2.1.0) └──[email protected]2.26.4 ([email protected], [email protected], [email protected].0, [email protected], [email protected], [email protected], [email protected], on-Heade[email protected]1.0.0, [email protected], [email protected], [email protected], [email protected].1.5, [email protected], [email protected], [email protected], [email protected], serve-[email protected]1.2.1, [email protected], [email protected], [email protected], [email protected]1.6.1, [email protected])

When NPM is complete, the Express 3.x and its dependencies are installed in the current Node_modules directory (this directory is automatically created, which is the installed dependency package). npm lsIt is possible to confirm that it will present express and its dependencies as the following tree structure.

[Email protected]/private/Tmp└─┬[email protected]3.0. 0beta7├──[email protected]0.6.1├─┬[email protected]2.3.9│├──[email protected]0.1.0│├──[email protected]0.0.4│├──[email protected]0.2.0│├──[email protected]1.0.11│└──[email protected]0.4.2├──[email protected]0.0.3├──[email protected]0.7.0├──[email protected]0.1.0├──[email protected]0.0.1├──[email protected]0.3.3├──range[Email protected]├─┬response[Email protected]│└──[email protected]0.2.0└─┬[email protected]0.0.3└──[email protected]1.2.6

The environment is ready, we can create an application, create a file in the directory App.js (anyway, the name casually, the habit is called app.js), the contents of App.js are as follows: (actually loaded into the express framework, let's create an application later)

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

Then you define the route, which responds to the path the user wants to access, and Express adds an encapsulated method to these objects, for example res.send() , it sets Content-length, as long as the Send method is called:

function (req, res) {  res.send (' Hello nodejs!! ') );});

Then app.listen() bind and listen to the connection by executing:

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

The above 3 paragraphs are app.js content.

Then launch the program, in the current directory directly hit "node App.js" can:

F:\hellonode>node App.js3000

Then access the http://127.0.0.1:3000/, the interface is as follows:

Launch a NODEJS application with express so easy!

Use Express to build an application

In fact, there is a more concise method, that is, using express to create a node application template, those files are not created by themselves, a direct command to the common files and packages are installed, which for us lazy people is really a century-old great benefits.

Run express MyApp to generate files for the following directories:

As prompted, CD mypp && npm Install and the node app will start the program.

If you want to build an application that supports jade, stylus, simply execute the following command:

 express --sessions --css stylus --ejs myapp

The software installed above is not global and is only useful under the current directory program.

Error handling

The error-handling middleware is the same as the normal middleware definition, except that it must have 4 parameters, which is its form: (err, req, res, next)

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

Generally, non-mandatory error handling is typically defined at the end, and the following code shows what is left app.use() behind:

App.use (Express.bodyparser ()); App.use (Express.methodoverride ()); App.use (App.router); App.use (  function(err, req, res, next) {  //  logic});

The responses in these middleware can be arbitrarily defined and can return any content, such as an HTML page, a simple message, or a JSON string.

For some organizations or higher-level frameworks, it is possible to define some of the error-handling middleware as if it were a normal middleware. Suppose you want to define a middleware that treats error handling by XHR and other requests differently, you can do this:

App.use (Express.bodyparser ()); App.use (Express.methodoverride ()); App.use (App.router); App.use (logErrors); app.use (Clienterrorhandler); App.use (ErrorHandler);

Often logErrors used to record error messages such as stderr, loggly, or similar services:

function logerrors (Err, req, res, next) {  console.error (err.stack);  Next (err);}

clientErrorHandlerAs defined below, note that the error is passed backwards very clearly.

function Clienterrorhandler (Err, req, res, next) {  if  (req.xhr) {    res.send ($, {error: ') Something blew up! '  });   Else {    Next (err);}  }

The following errorHandler "Catch all" exception is defined as:

function ErrorHandler (Err, req, res, next) {  res.status (+);  Res.render (' error ', {error:err});}

Get started with Express (node. JS Web application Framework)

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.