Express 4.x
Expressとは
公式サイト
http://expressjs.com/
「API Reference」で細かい仕様が記載されている。
「Community」の中の「Examples」にサンプルコードがけっこうある。
概要
Node.js上で動作するWebアプリのフレームワーク
アクセスURLを解析して処理を分岐する、ルーティングという機能がある。
ルーティング以外の各処理は、ミドルウェアとよばれる関数にまとめられる。
「ejs」「ect」「haml」「jade」など、いろいろなテンプレートエンジンを使用してビューを記述できます。
Expressのサンプルプログラムをインストール
Expressをインストール 今回は、グローバル環境にインストールします。 なお、今回の検証では、バージョン 4.13.1 を使用しました。
# npm install express –g
expressコマンドについて Express をグローバル環境にインストールすると、express というコマンドが使えるようになります。 「express -h」でヘルプを見れます。 Expressのサンプルプログラム express コマンドのあとにディレクトリ名を指定すると、そこにアプリケーションのひな形を作ってくれます。
# express express-sample
expressに依存するモジュールをインストールしましょう。
# cd express-sample # npm install
Express で内部ログを表示するには、アプリケーションの起動時に DEBUG 環境変数を express:* に設定します。
# DEBUG=express-sample:* npm start
Express を起動します。
# node bin/www
Expressにアクセスしてみましょう。 http://182.50.xx.xxx:3000 「Welcom to Express」と表示されれば正常に起動しています。
サンプルプログラムの中身
サンプルプログラムの中身の説明です。
- app.js はアプリケーションの本体
- node_modules が依存するモジュール
- package.json はアプリケーションのメタ情報とか依存するモジュールの情報が書かれたもの
- public は静的なファイル(画像ファイル、CSS ファイル、JavaScript ファイルなど)が入る
- routes には、ロジックが書かれたファイルが入る
- views はテンプレートが入る
基本的なルーティング
基本的なルーティング処理について説明します。
▼/express-myapp/rooute_sample.js
var express = require('express'), app = express(); app.get('/', function(req, res){ res.send('TOPページ'); }); app.get('/about', function(req, res){ res.send('aboutページ'); }); app.listen(3000); console.log("server start!");
▼起動
# node rooute_sample
▼解説
まずは Express のモジュールを読み込んでいます。var express = require('express'); app = express(); とすると、express を使ってオブジェクトを作ってくれます。app.get(‘/’, function() { })」で「/」でアクセスしてきたら次のことをしなさいという命令を書いています。これは、ルーティングと呼ばれるものです。 res.send()でメッセージを表示しています。
プレースホルダーを使う
▼/express-myapp/sample.js
var express = require('express'), app = express(); app.get('/users/:name?', function(req, res){ if (req.params.name) { res.send('hello,'+ req.params.name); } else { res.send('hello, 名無し'); } }); app.get('/items/:id([0-9]+)', function(req, res){ res.send('item no:'+ req.params.id); }); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
「app.get(‘/users/:name?’, …」とすると、name の値を「function(req, res) { … }」の中で使うことができます。(プレースホルダー) パラメータに正規表現である程度の制限をかけることもできます。例 「‘/items/:id([0-9]+)’」
ファイルを転送する
ファイルを転送
▼/express-myapp/sample.js
var express = require('express'), app = express(); app.get('/hello.txt', function(req, res){ res.sendfile(__dirname + '/public/hello.txt'); }); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
res.sendfileでファイル/public/hello.txtを読み込み転送しています。
静的ファイルを表示する
▼/express-myapp/sample.js
var express = require('express'), app = express(); app.use(express.static(__dirname + '/public')); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
app.use の experss.static を使用するとルーティングすることなくアクセスしたURLに応じて静的ファイル(/public/about.txt)をそのまま表示できる。 イメージ、CSS ファイル、JavaScript ファイルなどの静的ファイルを読み込む際に使用するとよいです。
ミドルウエアを使う
▼sample.js
var express = require('express'), app = express(); // useで呼ばれるものは、ミドルウエアと呼ばれてます。 app.use(express.static(__dirname + '/public')); // Routing (URLで該当している場合に処理) app.get('/hello.txt', function(req, res) { res.send('hello!!'); }); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
app.useで関数(ミドルウエア)を呼び出せる。 app.use で読み込まれるものは、ミドルウエアと呼ばれる。 expressフレームワークの中は、モジュールを読み込んで使う関数のことをミドルウェアと呼んでいます。 ミドルウェアは、expressに同梱されているものと、別途モジュールをインストールすることで使えるミドルウェアがある。
Node.js を再起動しなくてもいいようにする
今までソースに修正を加えたら、 Node.js を再起動してきましたが、それをしなくていいようなモジュールもあるので、インストールしましょう。
# npm install nodemon -g
node.js を自動起動するツールはいくつかリリースされてる。foreverとか・・
morganでログを出力してみよう
▼ターミナル morganをインストールしてロギングしているので入れておきましょう。
# npm install morgan
▼sample.js
var express = require('express'), app = express(); var morgan = require('morgan'); // ミドルウエア app.use(function(req, res, next) { console.log("ここはミドルウェアです。"); next(); }); // Routing (getなどはRoutingに関わる処理。リクエストによって処理するしないを判定) app.get('/hello.txt', function(req, res) { res.send('hello!!'); }); // LOGING app.use(morgan('short')); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
app.use(morgan('short'));で短いログを出力しています。
ejsテンプレートを使おう
まずは、ejsをインストールしましょう。
# npm install ejs
▼/views/index.ejs
<html> <head> <title><%= title %></title> </head> <body> <%= title %> <hr> <p>これは、ejsのテンプレートです。</p> </body> </html>
▼sample.js
var express = require('express'), app = express(); var morgan = require('morgan'); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); // ミドルウエア app.use(function(req, res, next) { console.log("ここはミドルウェアです。"); next(); }); // Routing app.get('/', function(req, res) { res.render('index', {title: 'タイトル'}); }); // LOGING app.use(morgan('short')); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼解説
どのテンプレートエンジンを使うかというのを 'view engine' で指定します。 テンプレートの中での変数表示は、<%= title %>のようにします。 テンプレートの中で使用する値は res.render の第 2 引数にオブジェクトで渡します。
URLパラメータを取得する
▼sample.js
var express = require('express'), app = express(); var morgan = require('morgan'); // ミドルウエア app.use(function(req, res, next) { console.log("ここはミドルウェアです。"); next(); }); app.param('id', function(req, res, next, id) { var users = ['田中', '佐藤', '小林']; req.params.name = users[id]; next(); }); app.get('/hello/:id', function(req, res) { res.send('hello ' + req.params.name); }); // LOGING app.use(morgan('short')); app.listen(3000); console.log("server start!");
▼起動
# node sample
▼アクセス例
http://xxx.xxx.xxx.xxx:3000/hello/1/
▼解説
ルーティングの処理の中で出てきたパラメータに対して共通処理をしたい場合は、 app.paramでできます。 idがある場合は、get が呼ばれる前に app.param が呼ばれる。
POSTされたデータを受け取ろう
▼必要なものをインストール bodyParser.json jsonとurlencodedの両middlewareもexpressにバンドルされていないので、後継であるbody-parserを使う。
# npm install body-parser
▼sample.js
var express = require('express'), app = express(); var bodyParser = require('body-parser'); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); // ミドルウエア app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // routing app.get('/new', function(req, res) { res.render('new'); }); app.post('/create', function(req, res) { res.send(req.body.name); }); app.listen(3000); console.log("server starting...");
▼/views/new.ejs
<html> <form method="post" action="/create"> <input type="text" name="name"> <input type="submit" value="create!"> </form> </html>
▼起動
# node sample
▼アクセス方法
http://xxx.xx.xx.xxx:3000/new
▼解説
app.use(bodyParser.json());とapp.use(bodyParser.urlencoded({ extended: true }));でリスクエストの処理方法を記載しています。ここは、ルーティングの前に必ずなくてはいけない。 post で渡ってきたものは req.body で取れる。
------------------------------
作成日:2016年06月25日
更新日:2016年06月25日
------------------------------