TIL Day 33 Express framework

31209 ワード

リファレンス

  • Node.js公式ドキュメント
    https://expressjs.com/ko/
  • Expressバー

  • Webおよびモバイルアプリケーションのための簡潔で柔軟なノード.js Webアプリケーションのフレームワークが大きい.
  • 高速実行方法

    mkdir 폴더이름
    cd 폴더이름
    // 폴더로 들어감
    npm init
    //package.json 파일 생성
    npm install express --save
    npm install express

    Expressの基本形態

    const express = require('express') //express 불러옴
    const app = express() //express를 실행한 객체를 app에 할당
    const port = 3000 //3000번 포트 설정
    app.get('/', (req, res) => { //app에 get + 엔드포인트가 '/'인 요청이 올 때 'Hello World'를 리턴한다.
      res.send('Hello World!')
    })
    app.listen(port, () => { //app에 3000번 포트를 연결
      console.log(`Example app listening at http://localhost:${port}`)
    })

    デフォルトのルーティング

  • ルーティングは、URI(パス)および特定のHTTP要求方法によって要求に対する応答を決定する.
  • きほんこうぞう

    app.METHOD(PATH, HANDLER)
    //app : express의 인스턴스
    //method : HTTP 요청 메소드
    //path : 서버에서의 경로
    //handler : 라우트가 일치할 때 실행되는 함수
    ex)
    app.get('/', function (req, res) {
      res.send('Hello World!');
    });
    app.post('/', function (req, res) {
      res.send('Got a POST request');
    });
    app.put('/user', function (req, res) {
      res.send('Got a PUT request at /user');
    });
    app.delete('/user', function (req, res) {
      res.send('Got a DELETE request at /user');
    });

    ルート


    ルーティングのデフォルトの例

    var express = require('express');
    var app = express();
    // respond with "hello world" when a GET request is made to the homepage
    app.get('/', function(req, res) {
      res.send('hello world');
    });

    ルーティングパス

  • ルーティング経路は、要求方法との組み合わせによって、要求を実現することができるエンドポイントを定義する.
  • ex)
    app.get('/', function (req, res) {
      res.send('root');
    });
    app.get('/about',function(req,res){
      res.send('about')
    })
    app.get('/random.text',function(req,res){
      res.send('random.text')
    })

    ルーティングマネージャ

  • は、要求を処理するために、学習されるミドルウェアと同様の複数のコールバック関数を提供する.唯一の違いは、このコールバックは、next(「route」)を呼び出すことによって、残りのルーティングコールバックを迂回することができることである.
  • ex)2つのコールバック関数が1つのルーティングを処理する
    app.get('/example/b', function (req, res, next) {
      console.log('the response will be sent by the next function ...');
      next(); //다음 콜백함수를 연결
    }, function (req, res) {
      res.send('Hello from B!');
    });
    ex)コールバック関数配列がルーティングを処理する
    var cb0 = function (req, res, next) {
      console.log('CB0');
      next();
    }
    var cb1 = function (req, res, next) {
      console.log('CB1');
      next();
    }
    var cb2 = function (req, res) {
      res.send('Hello from C!');
    }
    app.get('/example/c', [cb0, cb1, cb2]);
    ex)独立関数と配列の組み合わせによるルーティング
    var cb0 = function(req,res,next){
      console.log('CB0')
      next();
    }
    var cb1 = function(req,res,next){
      console.log('CB1')
      next();
    }
    app.get('/example/d',[cb0,cb1],function(req,res,next){
      console.log('the response will be sent by the next function...')
      next()
    },function(req,res){
      res.send('Hello from D!')
    })

    レスポンスメソッド

  • 応答オブジェクトの方法(res)は、応答をクライアントに送信し、要求応答サイクルを終了することができる.

  • メソッド説明res.end()応答プロセスは、res.json()JSON応答送信res.send()を8ビットストリームで送信するres.sendFile()ファイルの送信を終了する

    app.route()

  • ルーティング経路のためにチェーンルーティングハンドルを記述することができる.
  • app.route('/book')
      .get(function(req, res) {
        res.send('Get a random book');
      })
      .post(function(req, res) {
        res.send('Add a book');
      })
      .put(function(req, res) {
        res.send('Update the book');
      });

    express.Router

  • 異なる経路のルータモジュールを実行する関数
  • //bird.js에 작성
    var express = require('express');
    var router = express.Router();
    // middleware that is specific to this router
    router.use(function timeLog(req, res, next) {
      console.log('Time: ', Date.now());
      next();
    });
    // define the home page route
    router.get('/', function(req, res) {
      res.send('Birds home page');
    });
    // define the about route
    router.get('/about', function(req, res) {
      res.send('About birds');
    });
    module.exports = router;
    //기본 라우터 설정
    var bird = require('./birds')
    app.use('/birds',birds)
    // /birds로 끝나는 엔드포인트를 입력할 경우 birds.js로 이동

    Expressアプリケーション用のミドルウェアの作成

  • ミドルウェア関数とは、req、res、およびアプリケーションのリクエスト応答サイクルにおいて、次のミドルウェア関数にアクセス権を有する関数を指す.
    通常はnextの名前で変数を作成します.
  • var express = require('express');
    var app = express();
    //미들함수 생성
    var requestTime = function (req, res, next) {
      req.requestTime = Date.now();
      next(); //다음 미들함수를 호출
    };
    app.use(requestTime); //미들함수를 지정하여 호출하는 함수
    //미들웨어의 로드 순서는 중요하며, 먼저 로드되는 미들웨어 함수가 먼저 실행된다.
    //루트 경로에 대한 라우팅 이후에 myLogger가 로드되면, 루트 경로의 라우트 핸들러가 요청-응답 주기를 종료하므로 요청은 절대로 myLogger에 도달하지 못하며 앱은 “LOGGED”를 인쇄하지 않된다..
    app.get('/', function (req, res) {
      var responseText = 'Hello World!';
      responseText += 'Requested at: ' + req.requestTime + '';
      res.send(responseText);
    });
    app.listen(3000);