Node.js学習の道24——Expressフレームのアプリオブジェクト
8935 ワード
1.express()は、Node.jsプラットフォームに基づいて、急速に、開放的で、極めて簡単なウェブ開発の枠組みである. 作成 です. である. を生成します. を設定します. を設定します. に続く. に設定します.
1.2.
注:
1.3.基本的なHTTPサーバの構築は、 をカスタマイズすることができる. は、指定されたコールバック関数を有する指定経路 にHTTP削除要求をルーティングする.は は、 を有効にします. は、テンプレートエンジンの拡張子に応じて、異なるテンプレート を使用する. は、 にルーティングする. 傍受ポート、ホスト、最大接続数、コールバック関数 フィードバックトリガーをルーティングパラメータに追加します.名前はパラメータの名前またはそれらの配列で、関数はコールバック関数です.コールバック関数のパラメータは要求対象、応答オブジェクト、次の中間部品およびそのパラメータの値です.
nameが配列である場合は、ステートメントの順序で各パラメータを登録します.また、宣言された各パラメータについては、最後の他に、コールバック中の次の呼出は次の宣言のパラメータのコールを行います.最後のパラメータについては、nextを呼び出して、現在処理中のルートの次の中間部品を呼び出します.名前が文字列だけの場合と同じです.引数は、文字列 です.パラメータは、行列 です.は、アプリケーションの正規化経路 に戻る. コールバック関数は、ビューの提示HTML を返します.
1.15.ルーティング設定 は、単一のルーティングの例 を返す. は、パスにミドル関数を搭載しています.パスが指定されていない場合、デフォルトは です.パスは、経路、経路パターン、整合経路を表す正規表現またはその組み合わせ配列を表す文字列 でありうる. があり得る.使用できるところ 中間部品例 をトリガしません.
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
、オブジェクトはオプションで、以下の属性をサポートします.dotfiles
、String
、サービスdotfiles
のオプション.可能な値はallow
、deny
、ignore
、ignore
、標準値はmaxAge
Cache-Control
は、最大属性またはms
フォーマットの文字列をミリ秒単位で設定し、デフォルトは0
etag
、Boolean
タイプで、etag
を有効または無効にしてextensions
、Mixed
、ファイル拡張index
、Boolean
タイプ、ディレクトリインデックスを送信し、false
を無効にするredirect
タイプ、Boolean
タイプ、パスがディレクトリである場合、リダイレクトは/
、etHeaders
、Function
タイプで、HTTP
ヘッダをファイル用の関数1.2.
Etag
ETag
はHTTP1.1
においてのみ加入された属性は、サーバの制御を支援するために使用される.Web
端末のキャッシュ検証は、ブラウザがサーバのあるリソースを要求するときの原理である.A
の場合、サーバーはA
は、ハッシュ値を算出する.(3f80f-1b6-3e1cb03b)
を通過しますETag
はブラウザに戻ります.ブラウザは3f80f-1b6-3e1cb03b
とA
は同時にローカルにキャッシュされ、次回サーバに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 ...])
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){...})
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');
})