Node.js学習の道24——Expressフレームのアプリオブジェクト


1.express()
  • は、Node.jsプラットフォームに基づいて、急速に、開放的で、極めて簡単なウェブ開発の枠組みである.
  • 作成Expressアプリケーションexpress()は、expressモジュール導出の入口top-level関数
    const express = require('express');
    let app = express();
    1.1静的資源管理
  • express.static(root, [options])
  • express.staticは、Expressに内蔵されている唯一のミドルウェアであり、serve-staticに基づいて開発されたもので、ホストExpressのアプリケーション内の静的リソースを担当しています.
  • root、パラメータは、静的リソースファイルが存在するルートディレクトリを意味します.
  • options、オブジェクトはオプションで、以下の属性をサポートします.
  • dotfilesString、サービスdotfilesのオプション.可能な値はallowdenyignoreignore、標準値はmaxAge
  • です.
  • Cache-Controlは、最大属性またはmsフォーマットの文字列をミリ秒単位で設定し、デフォルトは0
  • である.
  • etagBooleanタイプで、etagを有効または無効にして
  • を生成します.
  • extensionsMixed、ファイル拡張
  • を設定します.
  • indexBooleanタイプ、ディレクトリインデックスを送信し、falseを無効にする
  • を設定します.
  • redirectタイプ、Booleanタイプ、パスがディレクトリである場合、リダイレクトは/
  • に続く.
  • etHeadersFunctionタイプで、HTTPヘッダをファイル用の関数
  • に設定します.
    1.2.EtagETagHTTP1.1においてのみ加入された属性は、サーバの制御を支援するために使用される.Web端末のキャッシュ検証は、ブラウザがサーバのあるリソースを要求するときの原理である.Aの場合、サーバーはAは、ハッシュ値を算出する.(3f80f-1b6-3e1cb03b)を通過しますETagはブラウザに戻ります.ブラウザは3f80f-1b6-3e1cb03bAは同時にローカルにキャッシュされ、次回サーバにAを要求すると、同様のようになる.If-None-Match: "3f80f-1b6-3e1cb03b"の要求ヘッドETagはサーバに送信し、サーバは再度計算する.Aのハッシュ値は、ブラウザから返された値と比較される.Aが変化したら、Aをブラウザに戻します.200、もし発見されたらA変化なしにブラウザに戻ります.304は変更されていません.このようにブラウザ側のキャッシュを制御することにより、サーバの帯域幅を節約することができます.サーバは毎回フルデータをクライアントに返す必要がないからです.
    注:HTTPには、ETagを生成する方法が指定されていません.ハッシュは理想的な選択です.
    1.3.基本的なHTTPサーバの構築
    const express = require('express');
    let app = express();
    
    app.get('/', (req, res) => {
        res.send('hello world');
    });
    
    app.listen(3000);
    1.4.appオブジェクトのlocals属性
  • は、localsオブジェクト上で属性
  • をカスタマイズすることができる.
  • app.locals.title = 'my express title';
  • app.locals.email = '[email protected]';
  • { settings: { 
        'x-powered-by': true,
         etag: 'weak',
         'etag fn': [Function: wetag],
         env: 'development',
         'query parser': 'extended',
         'query parser fn': [Function: parseExtendedQueryString],
         'subdomain offset': 2,
         'trust proxy': false,
         'trust proxy fn': [Function: trustNone],
         view: [Function: View],
         views: 'E:\\Self\\point\\views',
         'jsonp callback name': 'callback' 
        },
        title: 'my express title',
        email: '[email protected]'
    }
    1.5.app.all(path, callback(req, res, next){...})
    app.all('*', fn1, fn2...)
    //    
    app.all('*', fn1)
    app.all('*', fn2)
    1.6.削除要求ルーティング
  • app.delete(path, callback [, callback ...])
  • は、指定されたコールバック関数を有する指定経路
  • にHTTP削除要求をルーティングする.
    app.delete('/', function (req, res) {
        res.send('DELETE request to homepage');
    });
    1.7.属性の有効化を無効にする
  • app.disable(name)を無効にし、app.disabled(name)
  • は、app.able(name)を有効にし、app.abled(name)
  • を有効にします.
    app.set('username', 'express server');
    console.log(app.get('username')); //express server
    
    app.set('username', 'express server');
    app.disable('username');
    console.log(app.get('username')); //false
    1.8.テンプレートエンジン
  • app.engine(ext, callback)
  • は、テンプレートエンジンの拡張子に応じて、異なるテンプレート
  • を使用する.
    app.engine('jade', require('jade').__express);
    app.engine('html', require('ejs').renderFile);
    1.9.属性の設定と取得
    app.set('title', 'text');
    console.log(app.get('title')); // text
    1.10.get要求
  • app.get(path, callback [, callback ...])
  • は、HTTP取得要求を、指定されたコールバック関数を有する指定経路
  • にルーティングする.
    app.get('/', function (req, res) {
        res.send('GET request to homepage');
    });
    1.11.傍受ポート
  • app.listen(port, [hostname], [backlog], [callback(err)])
  • 傍受ポート、ホスト、最大接続数、コールバック関数
  • const express = require('express');
    let app = express();
    
    app.get('/', function (req, res) {
        res.send('home page');
    });
    
    app.listen(3000, 'localhost', 100, function (err) {
        if (err) {
            console.log('error');
        } else {
            console.log('the http server is running at localhost:3333');
        }
    });
    1.12.ルートパラメータ
  • app.param([name],callback(req, res, next, id){...})
  • フィードバックトリガーをルーティングパラメータに追加します.名前はパラメータの名前またはそれらの配列で、関数はコールバック関数です.コールバック関数のパラメータは要求対象、応答オブジェクト、次の中間部品およびそのパラメータの値です.
    nameが配列である場合は、ステートメントの順序で各パラメータを登録します.また、宣言された各パラメータについては、最後の他に、コールバック中の次の呼出は次の宣言のパラメータのコールを行います.最後のパラメータについては、nextを呼び出して、現在処理中のルートの次の中間部品を呼び出します.名前が文字列だけの場合と同じです.
  • 引数は、文字列
  • です.
    app.param('id', (req, res, next, id) => {
        console.log('called only once');
        next();
    });
    
    app.get('/user/:id', (req, res, next) => {
        console.log('although this matches');
        next();
    });
    
    app.get('/user/:id', (req, res) => {
        console.log('this matches too');
        res.send('end user id');
    });
    /**
    called only once
    although this matches
    this matches too
    */
  • パラメータは、行列
  • です.
    app.param(['id', 'page'], (req, res, next, id) => {
        console.log('called only once', id);
        next();
    });
    
    app.get('/user/:id/:page', (req, res, next) => {
        console.log('although this matches');
        next();
    });
    
    app.get('/user/:id/:page', (req, res) => {
        console.log('this matches too');
        res.send('end user id');
    });
    /**
    called only once kkk
    called only once 555
    although this matches
    this matches too
    */
    1.13.app.path()
  • は、アプリケーションの正規化経路
  • に戻る.
    let express = require('express');
    let app = express();
    let blog = express();
    let blogAdmin = express();
    
    app.use('/blog', blog);
    blog.use('/admin', blogAdmin);
    
    console.log(app.path());
    console.log(blog.path());
    console.log(blogAdmin.path());
    1.14.テンプレートレンダリング
  • app.render(view, [locals], callback(err,html){...})
  • コールバック関数は、ビューの提示HTML
  • を返します.
    1.15.ルーティング設定
  • app.route(path)
  • は、単一のルーティングの例
  • を返す.
    app.route('/one')
        .all(function (req, res, next) {
            console.log('route all');
            next();
        })
        .get(function (req, res, next) {
            res.json({
                code: 2589,
                msg: 'route get msg'
            });
        })
        .post(function (req, res, next) {
            res.send('this is route post send msg');
        });
    1.16.ミドルウェア
  • app.use([path,] callback(req, res, next){...})
  • は、パスにミドル関数を搭載しています.パスが指定されていない場合、デフォルトは/
  • です.
  • パスは、経路、経路パターン、整合経路を表す正規表現またはその組み合わせ配列を表す文字列
  • でありうる.
  • app.use()ミドルウェアは、正規マッチングパスを使用することができ、複数のミドルウェア関数
  • があり得る.
  • 使用できるところ
  • app.use(express.static(__dirname + '/public'));
    app.use('/static', express.static(__dirname + '/public'));
    app.use(express.static(__dirname + '/public'));
    app.use(logger());
    app.use(express.static(__dirname + '/public'));
    app.use(express.static(__dirname + '/files'));
    app.use(express.static(__dirname + '/uploads'));
  • 中間部品例
  • app.use('/user/person', (req, res, next) => {
        console.log(req.originalUrl); // /user/person
        console.log(req.baseUrl); // /user/person
        console.log(req.path); // /
        next();
    });
  • app.use(callback())を使用すると、app.get('/', callback())
  • をトリガしません.
    // this middleware will not allow the request to go beyond it
    app.use((req, res, next) => {
        res.send('Hello World');
    })
    
    // requests will never reach this route
    app.get('/', (req, res) => {
        res.send('Welcome');
    })