Express 4に移動中
エクスプレス4はエクスプレス3からの変更です。 つまり、Expressバージョンを依存関係で更新すると、既存のExpress 3アプリは動作しなくなります。
この記事のカバー:
Express 4の変更
Express 4にはいくつかの大きな変更点があります。
Express core システムとミドルウェアシステムに変更しました。 Connectとビルトインミドルウェアの依存関係が削除されましたので、自分でミドルウェアを追加する必要があります。
- ルーティングシステムへの変更。
- その他の様々な変更。
こちらもご参照ください:
- [新機能 in 4.x] (https://github.com/expressjs/express/wiki/New-features-in-4.x)
- Migrating from 3.x to 4.x
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.
組み込みのミドルウェアがなければ、アプリケーションの実行に必要なすべての ミドルウェアを明示的に追加する必要があります。 以下の手順に従ってください:
- モジュールをインストール:
npm install --save \<module-name> - アプリでは、次のモジュールを必要とします:
require('module-name') - ドキュメントに従ってモジュールを使用します:
app.use( ... )
以下の表は、Express 4でのExpress 3ミドルウェアとそのミドルウェアを示しています。
| エクスプレス 3 | エクスプレス 4 |
|---|---|
express.bodyParser | |
express.compress | 圧縮 |
express.cookieSession | クッキーセッション |
express.cookieParser | クッキーパーサ |
express.logger | モーガン |
express.session | express-session |
express.favicon | サービスファビコン |
express.responseTime | 応答時間 |
express.errorHandler | errorhandler |
express.methodOverride | メソッド-オーバーライド |
express.timeout | 接続タイムアウト |
express.vhost | vhost |
express.csrf | csurf |
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 routerrouter.use((req, res, next) => { console.log('Time: ', Date.now()); next();});// define the home page routerouter.get('/', (req, res) => { res.send('Birds home page');});// define the about routerouter.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.js | Express 4 は Node.js 0.10.x 以降が必要で、Node.js 0.8.x のサポートを廃止しました。 |
http.createServer() |
|
app.configure() |
|
json spaces | Express 4では、 |
req.accepted() |
|
res.location() | 相対URLを解決しなくなりました。 |
req.params | 配列で、現在はオブジェクトです。 |
res.locals | 関数でした; 今はオブジェクトです。 |
res.headerSent | res.headersSent に変更しました。 |
app.route | app.mountpath として利用可能になりました。 |
res.on('header') | 削除しました。 |
res.charset | 削除しました。 |
res.setHeader('Set-Cookie', val) | 機能は基本的なクッキー値の設定に限定されるようになりました。 追加された 機能には、
|
アプリの移行例
Express 3アプリケーションをExpress 4に移行する例を以下に示します。
関心のあるファイルは app.js と package.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 environmentsapp.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 onlyif (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を最新の バージョンにアップデートして移行を開始します。
$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --saveapp.jsに以下の変更を加えます。
-
組み込みの Express ミドルウェア関数
express.favicon,express.logger,express.methodOverride,express.session,express.bodyParserとexpress.errorHandlerは、expressオブジェクトでは使用できなくなりました。 代わりの を手動でインストールし、アプリにロードする必要があります。 -
app.router関数をロードする必要がなくなりました。 有効なExpress 4アプリオブジェクトではないため、app.use(app.router);コードを削除します。 -
ミドルウェア関数が正しい順序でロードされていることを確認してください - アプリのルートをロードした後に
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 environmentsapp.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 routesif (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アプリになりました。 確認するには、次のコマンドを使用してアプリを起動します。
$ 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アプリジェネレータがシステムにインストールされている場合、 アンインストールする必要があります。
$ npm uninstall -g expressファイルとディレクトリ権限の設定に応じて、
sudo でこのコマンドを実行する必要があります。
新しいジェネレータをインストールします。
$ npm install -g express-generatorファイルとディレクトリ権限の設定に応じて、
sudo でこのコマンドを実行する必要があります。
システムの express コマンドが
Express 4ジェネレータに更新されます。
アプリジェネレーターの変更
コマンドオプションと使用方法は、以下の例外を除き、ほとんど同じままです。
--sessionsオプションを削除しました。--jshtmlオプションを削除しました。- Hogan.js をサポートするための
--hoganオプションを追加しました。
例
Express 4 アプリを作成するには、次のコマンドを実行します。
$ express app4If 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モジュールは、古いジェネレータによって生成されたスタンドアロンアプリとは対照的に。
依存関係をインストールした後、次のコマンドを使用してアプリを起動します。
$ npm startIf 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.