NodeJS :追加のミドルウェアをExpressサーバーに追加する方法



イントロ
それで、我々は我々の機械に乗っています.
私たちも学びました.
今、我々はどのように追加のミドルウェアを我々のExpressサーバーに追加する方法を学びたい.

からの我々の単純なサーバーを再利用してください
  • 端末を開く
  • ファイル名index.js :
  • touch index.js
    
  • このJavaScriptコードを追加します.
  • const express = require('express');
    const app = express();
    
    const PORT = 8080;
    
    app.get('/', (request, response) => {
      response.send('Hello World');
    });
    
    app.listen(PORT, () => {
      console.log(`Server running at: http://localhost:${PORT}/`);
    });
    
    注:これは私たちの出発点です、我々は1つの作業ルートを持っています.
    更新しましたreq to request & res to response 読みやすさを向上させる.

    追加ミドルウェア
    ミドルウェアとは
    既定のリクエスト応答サイクルの間に追加機能を追加する場合もあります.のは、現在の要求についての詳細な情報を取得したいとしましょう.
    あなたは、このタスクを処理する簡単なミドルウェアを書くことができますし、Expressのアプリに追加します.

    ミドルウェアを作る
  • ファイル名logger.js :
  • touch logger.js
    
  • このJavaScriptコードを追加します.
  • const logger = (req, res, next) => {
      console.log(`Time: ${new Date()} - Method: ${req.method} - Path: ${req.originalUrl}`);
      next();
    };
    
    module.exports = logger;
    
  • インデックスに新しいロガーが必要です.JSとミドルウェアを使用します
  • // import express (after npm install express)
    const express = require('express');
    
    // import the logger
    const logger = require('./logger');
    
    // create new express app and save it as app
    const app = express();
    
    // server configuration
    const PORT = 8080;
    
    // use the middleware
    app.use(logger);
    
    // create a route for the app
    app.get('/', (req, res) => {
      res.send('Hello World');
    });
    
    // make the server listen to requests
    app.listen(PORT, () => {
      console.log(`Server running at: http://localhost:${PORT}/`);
    });
    

    端末から実行する
  • 実行する
  • node index.js
    
  • 訪問http://localhost:8080
  • コンソール結果:
  • Server running at: http://localhost:8080/
    Time: Tue Sep 03 2019 17:32:30 GMT+0200 (Central European Summer Time) - Method: GET - Path: /
    

    ExpressとPostgreSQLのシリーズ
    ここでは見つけることができます

    更なる読書
  • express
  • Using Middleware
  • app.use()
  • Middleware callback function examples

  • 質問
  • あなたの好きなミドルウェアは何ですか.