Express 4に移動中

エクスプレス4はエクスプレス3からの変更です。 つまり、Expressバージョンを依存関係で更新すると、既存のExpress 3アプリは動作しなくなります。

この記事のカバー:

Express 4の変更

Express 4にはいくつかの大きな変更点があります。

こちらもご参照ください:

Express coreとミドルウェアシステムへの変更

Express 4はもうConnectに依存せず、組み込みの ミドルウェアをコアから削除します。ただし、express.static関数は除外します。 This means that Express is now an independent routing and middleware web framework, and Express versioning and releases are not affected by middleware updates.

組み込みのミドルウェアがなければ、アプリケーションの実行に必要なすべての ミドルウェアを明示的に追加する必要があります。 以下の手順に従ってください:

  1. モジュールをインストール: npm install --save \<module-name>
  2. アプリでは、次のモジュールを必要とします: require('module-name')
  3. ドキュメントに従ってモジュールを使用します: app.use( ... )

以下の表は、Express 4でのExpress 3ミドルウェアとそのミドルウェアを示しています。

エクスプレス 3エクスプレス 4
express.bodyParser

body-parser + multer

express.compress圧縮
express.cookieSessionクッキーセッション
express.cookieParserクッキーパーサ
express.loggerモーガン
express.sessionexpress-session
express.faviconサービスファビコン
express.responseTime応答時間
express.errorHandlererrorhandler
express.methodOverrideメソッド-オーバーライド
express.timeout接続タイムアウト
express.vhostvhost
express.csrfcsurf
express.directoryサーブインデックス
express.staticスタティック

Here is the complete list of Express 4 middleware.

ほとんどの場合、古いバージョン3のミドルウェアを のExpress 4に置き換えることができます。 詳細については、 GitHub のモジュールドキュメントを参照してください。

app.useはパラメータを受け付けます

バージョン 4 では、変数 parameter を使用して、ミドルウェア関数がロードされるパスを定義できます。 次に、ルートハンドラからパラメータの値を読み込みます。 例:

app.use('/book/:id', (req, res, next) => {
console.log('ID:', req.params.id);
next();
});

ルーティング システム

Apps now implicitly load routing middleware, so you no longer have to worry about the order in which middleware is loaded with respect to the router middleware.

ルートの定義方法は変更されていませんが、ルーティングシステムにはルートの整理に役立つ2つの 新機能があります。

  • 新しいメソッド app.route() は、ルートパスに対してチェーン可能なルートハンドラを作成します。
  • モジュール式のマウント可能なルートハンドラを作成するための新しいクラス express.Router

app.route()メソッド

新しいapp.route()メソッドを使用すると、ルートパスのチェーン可能なルートハンドラ を作成できます。 パスは単一の場所で指定されているため、モジュラールートを作成することは、冗長性とタイプミスを削減するのに役立ちます。 For more information about routes, see Router() documentation.

以下は、app.route()関数を使用して定義されたルートハンドラの例です。

app
.route('/book')
.get((req, res) => {
res.send('Get a random book');
})
.post((req, res) => {
res.send('Add a book');
})
.put((req, res) => {
res.send('Update the book');
});

express.Router クラス

ルートを整理するのに役立つもう一つの機能は、新しいクラス express.Router で、モジュラーマウント可能な ルートハンドラを作成するために使用できます。 Routerインスタンスは完全なミドルウェアと ルーティングシステムです。このため、しばしば”mini-app”と呼ばれます。

The following example creates a router as a module, loads middleware in it, defines some routes, and mounts it on a path on the main app.

For example, create a router file named birds.js in the app directory, with the following content:

var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use((req, res, next) => {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', (req, res) => {
res.send('Birds home page');
});
// define the about route
router.get('/about', (req, res) => {
res.send('About birds');
});
module.exports = router;

次に、アプリにルーターモジュールをロードします。

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

The app will now be able to handle requests to the /birds and /birds/about paths, and will call the timeLog middleware that is specific to the route.

その他の変更

以下の表は、Express 4の他の重要な変更点を示しています。

オブジェクト説明
Node.jsExpress 4 は Node.js 0.10.x 以降が必要で、Node.js 0.8.x のサポートを廃止しました。
http.createServer()

httpモジュールは、 (socket.io/SPDY/HTTPS)で直接動作する必要がない限り、もはや必要ありません。 アプリは、app.listen()関数を使用して起動できます。

app.configure()

app.configure()関数が削除されました。 process.env.NODE_ENV または app.get('env') 関数を使用して環境を検出し、それに応じてアプリを構成します。

json spaces

Express 4では、json spaces アプリケーションプロパティはデフォルトで無効になっています。

req.accepted()

req.accepts()req.acceptsEncodings()req.acceptsCharsets()、および req.acceptsLanguages()を使用してください。

res.location()相対URLを解決しなくなりました。
req.params配列で、現在はオブジェクトです。
res.locals関数でした; 今はオブジェクトです。
res.headerSentres.headersSent に変更しました。
app.routeapp.mountpath として利用可能になりました。
res.on('header')削除しました。
res.charset削除しました。
res.setHeader('Set-Cookie', val)

機能は基本的なクッキー値の設定に限定されるようになりました。 追加された 機能には、 res.cookie() を使用します。

アプリの移行例

Express 3アプリケーションをExpress 4に移行する例を以下に示します。 関心のあるファイルは app.jspackage.json です。

バージョン3アプリ

app.js

次の app.js ファイルを含む Express v.3 アプリケーションを考えてみましょう。

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 environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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 only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'));
});

package.json

The accompanying version 3 package.json file might look something like this:

{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.12.0",
"pug": "*"
}
}

プロセス

以下のコマンドを使用して、 Express 4アプリに必要なミドルウェアをインストールし、ExpressとPugを最新の バージョンにアップデートして移行を開始します。

Terminal window
$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save

app.jsに以下の変更を加えます。

  1. 組み込みの Express ミドルウェア関数 express.favicon , express.logger , express.methodOverride , express.session , express.bodyParserexpress.errorHandler は、 express オブジェクトでは使用できなくなりました。 代わりの を手動でインストールし、アプリにロードする必要があります。

  2. app.router関数をロードする必要がなくなりました。 有効なExpress 4アプリオブジェクトではないため、 app.use(app.router); コードを削除します。

  3. ミドルウェア関数が正しい順序でロードされていることを確認してください - アプリのルートをロードした後に errorHandler をロードします。

バージョン4アプリ

package.json

上記の npm コマンドを実行すると、 package.json が以下のように更新されます。

{
"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",
"pug": "^2.0.0",
"method-override": "^2.1.2",
"morgan": "^1.2.2",
"multer": "^0.1.3",
"serve-favicon": "^2.0.1"
}
}

app.js

次に、無効なコードを削除し、必要なミドルウェアをロードし、必要に応じて他の 変更を行います。 app.jsファイルは次のようになります。

var http = require('http');
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 environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
app.use(logger('dev'));
app.use(methodOverride());
app.use(
session({
resave: true,
saveUninitialized: true,
secret: 'uwotm8',
})
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
app.get('/users', user.list);
// error handling middleware should be loaded after the loading the routes
if (app.get('env') === 'development') {
app.use(errorHandler());
}
var server = http.createServer(app);
server.listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'));
});

http モジュール (socket.io/SPDY/HTTPS) で直接作業する必要がない限り、読み込みは必要ありません。この方法でアプリを起動できます。

app.listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'));
});

アプリの実行

移行処理が完了し、アプリは エクスプレス4アプリになりました。 確認するには、次のコマンドを使用してアプリを起動します。

Terminal window
$ node .

http://localhost:3000 を読み込み、Express 4によってレンダリングされるホームページを参照してください。

Express 4アプリジェネレーターへのアップグレード

The command-line tool to generate an Express app is still express, but to upgrade to the new version, you must uninstall the Express 3 app generator and then install the new express-generator.

インストール中

すでにExpress 3アプリジェネレータがシステムにインストールされている場合、 アンインストールする必要があります。

Terminal window
$ npm uninstall -g express

ファイルとディレクトリ権限の設定に応じて、 sudo でこのコマンドを実行する必要があります。

新しいジェネレータをインストールします。

Terminal window
$ npm install -g express-generator

ファイルとディレクトリ権限の設定に応じて、 sudo でこのコマンドを実行する必要があります。

システムの express コマンドが Express 4ジェネレータに更新されます。

アプリジェネレーターの変更

コマンドオプションと使用方法は、以下の例外を除き、ほとんど同じままです。

  • --sessions オプションを削除しました。
  • --jshtml オプションを削除しました。
  • Hogan.js をサポートするための --hogan オプションを追加しました。

Express 4 アプリを作成するには、次のコマンドを実行します。

Terminal window
$ express app4

If you look at the contents of the app4/app.js file, you will notice that all the middleware functions (except express.static) that are required for the app are loaded as independent modules, and the router middleware is no longer explicitly loaded in the app.

app.jsファイルがノードになっていることにも気づくでしょう。 sモジュールは、古いジェネレータによって生成されたスタンドアロンアプリとは対照的に。

依存関係をインストールした後、次のコマンドを使用してアプリを起動します。

Terminal window
$ npm start

If you look at the npm start script in the package.json file, you will notice that the actual command that starts the app is node ./bin/www, which used to be node app.js in Express 3.

Because the app.js file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). モジュールは Node.js ファイル にロードされ、Node.js ファイルを介して開始する必要があります。 Node.js ファイルは ./bin/www です。

Expressアプリの作成やアプリの起動には、binディレクトリも拡張機能のないwww ファイルも必須ではありません。 それらは 発電機による提案ですので、 のニーズに合わせて変更してください。

To get rid of the www directory and keep things the “Express 3 way”, delete the line that says module.exports = app; at the end of the app.js file, then paste the following code in its place:

app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), () => {
debug('Express server listening on port ' + server.address().port);
});

app.jsファイルの先頭にあるdebugモジュールがロードされていることを確認します。

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

次に、 start": package.json ファイル中の "node ./bin/www""start": "node app.js" に変更します。

これで ./bin/www の機能を app.js に戻しました。 This change is not recommended, but the exercise helps you to understand how the ./bin/www file works, and why the app.js file no longer starts on its own.

HTTPS · expressjs.com
← Home