Express 4 Update Change document

Source: Internet
Author: User

Overview

From Express 3 to express 4 is a huge change, which means that the existing Express 3 app will not work without updating dependencies.

This article covers the following:

    • Changes in Express 4
    • An example of migrating from Express 3 to express 4
    • Upgrade to the Express 4 app Builder

Changes in Express 4

The main changes are as follows:

    • Express's core and middleware system: dependencies on Connect and built-in middleware are removed. So you have to add the middleware yourself.
    • Routing system
    • Other

See:

    • New features in 4.X
    • Migrating from 3.X to 4.X
Express's core and middleware system

Express 4 is no longer dependent on Connect and removes all built-in middleware from the core, in addition to express.static. This means that Express is now a WEB framework that does not rely on routing and middleware. The release and release of Express is no longer affected by middleware.

As the built-in middleware is removed, you must explicitly add all of the dependent middleware to run your application, which simply requires the following steps:

    1. Installation module: NPM install–save module Name
    2. In your application, use this module: Require (module name)
    3. module-based documentation to use modules

The following table lists the modules in Express 3 in the corresponding Express 4

Express 3 Express 4
Express.bodyparser Body-parser + multer
Express.compress Compression
Express.cookiesession Cookie-session
Express.cookieparser Cookie-parser
Express.logger Morgan
Express.session Express-session
Express.favicon Serve-favicon
Express.responsetime Response-time
Express.errorhandler ErrorHandler
Express.methodoverride Method-override
Express.timeout Connect-timeout
Express.vhost Vhost
Express.csrf Csurf
Express.directory Serve-index
Express.static Serve-static
Express.timeout Connect-timeout

For a complete list, see here: Https://github.com/senchalabs/connect#middleware

In most cases, you can replace the old module with the Express 3 module in Express 4, detailed instructions on GitHub documentation

Parameters accepted by App.use

In Express 4, you can now load the middleware with a path with a mutable parameter, and read the values of the parameters from the route processor, for example:

App.use ('/book/:id ', function (req, res, next) {  console.log (' ID: ', req.params.id);  Next ();})

Routing system

The application implicitly loads the routing middleware, so now you don't have to worry about the order of router routing middleware loading.

The way the route is defined has not changed, and two new features are now added to help organize the routing system.

    • New method route that creates a chained route processor for a routing path.
    • The new Class Express. Router, creating a modular routing processor

App.route method

The new App.route method creates a chained routing processor for a specific routing path. Because paths can be defined in one place, it helps to create routing rules for module sessions, reducing duplication.

For more information on routing, refer to the documentation for route ().

The following example shows the chained definition of a route

App.route ('/book ')  . Get (function (req, res) {    res.send (' Get a random book ');  })  . Post (function (req, res) {    res.send (' Add a book ');  })  . Put (function (req, res) {    res.send (' Update the book ');  })

Express. Router class

Another feature that helps organize routing is the new Class Express. Router, which can help create a routing processor for a module session. An example of a Router is a complete middleware and routing system, which is often referred to as a mini-application for this reason.

The following shows the creation of a route file named Bird.js, which reads as follows:

var express = require (' Express '); var router = Express. Router ();//middleware specific to this routerrouter.use (function TimeLog (req, res, next) {  Console.log (' Time: ', Dat E.now ());  Next ();}) Define the home page routerouter.get ('/', function (req, res) {  res.send (' Birds home Page ');}) Define the About Routerouter.get ('/about ', function (req, res) {  res.send (' About birds ');}) Module.exports = router;

The routing module is then loaded in the application.

var birds = require ('./birds '), .... App.use ('/birds ', birds);

This application can now handle requests/birds and/birds/about, and can also invoke TimeLog middleware.

Other changes

The following table lists other minor but important modifications

Object

Description

Node

Express 4 requires Node 0.10.x and above, 0.8.x is not supported

Http.createserver

The HTTP module is no longer needed and the app starts with App.listen ()

App.configure ()

App.configure () has been removed, using Process.env.NODE_ENV or App.get ("env") to detect the environment, configure the application

Json.spaces ()

JSON spaces is disabled by default in Express 4

Req.location ()

Relative URLs can no longer be obtained

Req.params

It turns out to be an array and is now an object

Res.locals

It turns out to be a function, now an object

Res.headersent

Modify to Res.headerssent

App.route

Now as App.mountpath exists

Res.on ("header")

Delete

Res.charset

Delete

Res.setheader ("Set-cookie", Val)

This feature is now limited to setting the basic cookie value, using the Add function of the Res.cookie ()

Example

Here is an example of an upgrade from Express 3 to express 4.

Version 3 App

App.js

The original app.js are as follows:

var express = require (' Express '); var routes = require ('./routes '); var user = require ('./routes/user '); var http = require (' http '); var path = require (' path '); var app = Express ();//All Environmentsapp.set (' Port ', Process.env.PORT | | |); app.se T (' views ', Path.join (__dirname, ' views ')), App.set (' View engine ', ' Jade '), App.use (Express.favicon ()); App.use ( Express.logger (' dev ')); App.use (Express.methodoverride ()); App.use (Express.session ({secret: ' Your Secret here ')); App.use (Express.bodyparser ()); App.use (App.router); App.use (Express.static (Path.join (__dirname, ' public '));// Development Onlyif (' development ' = = App.get (' env ')) {  app.use (Express.errorhandler ());} App.get ('/', Routes.index), App.get ('/users ', user.list), Http.createserver (APP) Listen (App.get (' Port '), function () {  Console.log (' Express server listening on port ' + app.get (' Port ');});

Package.json is shown below

{  "name": "Application-name",  "version": "0.0.1",  "private": True,  "scripts": {    "start": "Node App.js "  },  " dependencies ": {    " Express ":" 3.12.0 ",    " Jade ":" * "  }}
Migration process

Before migrating, install the middleware required for Express 4 and update Express,jade to the latest version.

$ npm Install Serve-favicon Morgan method-override express-sessionbody-parser multer ErrorHandler [email protected] [Emai L Protected]--save

Make a change to the app.js.

1. The HTTP module has been used, so remove the var http = require ("http");

2. Built-in middleware Express.favicon, Express.logger, Express.methodoverride, Express.session, Express.bodyparser and Express.errorhandler no longer exists, you must install them manually, and then replace them in your app.

3. No longer need to load app.router, in fact, it is not already an object in Express 4, so delete app.use (app.router);

4. Use App.listen () to replace http.createserver boot.

Version 4 App

Package.json

Execute the above command and the Package.json file will be updated as follows.

{  "name": "Application-name",  "version": "0.0.1",  "private": True,  "scripts": {    "start": "Node App.js "  },  " dependencies ": {    " Body-parser ":" ^1.5.2 ",    " ErrorHandler ":" ^1.1.1 ",    " Express ":" ^ 4.8.0 ",    " express-session ":" ^1.7.2 ",    " Jade ":" ^1.5.0 ",    " Method-override ":" ^2.1.2 ",    " Morgan ": "^1.2.2",    "Multer": "^0.1.3",    "Serve-favicon": "^2.0.1"  }}

App.js

Then, remove the invalid code, load the required middleware, complete the other necessary modifications, and the final app.js looks like this:

var express = require (' Express '); var routes = require ('./routes '); var user = require ('./routes/user '); var path = require (' Path '), var favicon = require (' Serve-favicon '), var logger = require (' Morgan '), var methodoverride = require (' Method-override ') var session = require (' express-session '); var bodyparser = require (' Body-parser '); var multer = require (' Multer '); var ErrorHandler = require (' ErrorHandler '); var app = Express ();//All Environmentsapp.set (' Port ', Process.env.PORT | | App.set (' Views ', Path.join (__dirname, ' views ')), App.set (' View engine ', ' Jade '), App.use (Favicon (__dirname + '/ Public/favicon.ico '), App.use (Logger (' dev ')), App.use (Methodoverride ()), App.use (session ({resave:true, SA Veuninitialized:true, Secret: ' Uwotm8 ')); App.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({ex Tended:true}); App.use (Multer ()); App.use (Express.static (Path.join (__dirname, ' public '));//Development Onlyif (' Development ' = = App.get (' env ')) {App.use (ErrorhAndler ());} App.get ('/', routes.index); App.get ('/users ', user.list); App.listen (' Port '), function () {App.get (' Express server listening on port ' + app.get (' Port ');});
Run the App

Now that the migration is complete, start with the following command.

$ node App

Use your browser to access http://localhost:3000 and view the pages generated using Express 4.

Upgrade to the Express 4 app Builder

To generate an express 4 command-line tool or express, however, to upgrade to the new version, you need to uninstall the Express 3 Generator, and then install the new generator.

Installation

If you have installed the generator for Express 3, you must first uninstall

NPM Uninstall–g Express

Depending on the permissions and configuration of your directory, you may need to perform sudo elevation permissions first.

Now, install the new generator

NPM install–g Express-generator

Now, the Express command in your system has been upgraded to the generator of Express 4.

Changes to the generator

In addition to the following changes, basically the same as before.

The--sessions option was removed

The--jshtml option was removed

--hogan is added in order to support Hogan.js

Example

Execute the following command to create the APP4 app

Express APP4

If you look at the App.js file in the App4 folder, you will find that all middleware is replaced with a standalone middleware load, and the router middleware is no longer explicitly loaded.

You'll also notice that App.js is now a Node module.

After installing the dependent files, start the app with the following command.

$ NPM Start

If you look at the startup script in Package.json, you'll notice that the actual startup script is node/bin/www, which is node app.js in Express 3.

As the Express 4 new app.js is already a node module, it can no longer need to be launched through a standalone application, it can be loaded in the node file, launched via node file, here is the./bin/www

Both the bin folder and the WWW file are generated manually by the Express generator, so you can modify it if you want.

In order to be consistent with Express 3, remove module.experts = app; at the end of App.js, add the following code.

App.set (' Port ', Process.env.PORT | |); var server = App.listen (app.get (' Port '), function () {  debug (' Express Server listening on port ' + server.address (). port);});

Confirm that the Debug module is loaded.

var debug = require (' Debug ') (' app4 ');

Then change the start: "node./bin/www" In the Package.json file to "Start": "Node App.js".

Now, it has returned to app.js from./bin/www.

Express 4 Update Change document

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.