ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • express.router
    JavaScript/Exress 2022. 10. 11. 20:03
    const router = express.Router([options])

    새로운 라우터 객체를 찍어낸다.


    옵션에 들어갈 수 있는 것들

    caseSensitive

    default 값이 disabled. 그간 열심히 '/posts' 를 '/Posts' 로 쓰지 않기 위해 기울였던 노력은 허사였다네.

     


    mergeParams

    Preserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.

     

    라우터 파라미터에 대한 고질적인 이슈.

     

    https://inmanustuaspater.tistory.com/115

     


     

    strict

    디폴트는 disabled. strict 한 routing이 뭔가 했더니, 이게 비활성화되어 있어서 '/경로' 와 '/경로/' 가 같은 것으로 취급되었다는듯.

    그러니까, 앞으로도 켤 일 없는 옵션이다.


    Router

    미들웨어를 돌리고 라우팅기능만 수행할 수있는 "mini application".

    (그런데 라우팅, 라우트 이거 한국 개발필드의 사투리더라. 그냥 공유기능, 아니면 멋들어지게 공화(共和)기능으로 하면 안되겠나. 돌아가는 것도 공화국의 대의제 기구 같잖아.) 

     

    하여튼 라우터 자체가 미들웨어라서. app.use() 에 인수로 혹은 심지어 다른 router.user()의 인수로도 들어갈 수 있다.

     

    "Once you’ve created a router object, you can add middleware and HTTP method routes (such as get, put, post, and so on) to it just like an application. For example:"

     

    // only requests to /calendar/* will be sent to our "router"
    app.use('/calendar', router)

    '/calendar' 를 거쳐서만 라우터로 들어간다.

    사실 그냥 프리픽스 경로설정이다.


    router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => {
      const from = req.params[0]
      const to = req.params[1] || 'HEAD'
      res.send(`commit range ${from}..${to}`)
    })

    정규식을 쓸 수도 있다.

    다음은 "GET /commits/71dbb9c" 및 "GET /commits/71dbb9c..4c084f9"와 일치한다고.

     


    function fn (req, res, next) {
      console.log('I come here')
      next('router')
    }
    router.get('/foo', fn, (req, res, next) => {
      console.log('I dont come here')
    })
    router.get('/foo', (req, res, next) => {
      console.log('I dont come here')
    })
    app.get('/foo', (req, res) => {
      console.log(' I come here too')
      res.end('good')
    })

     

     

    next 의 활용에 대한 예제.


     

    미들웨어는 "배관 파이프" 와 같다고 표현한다.

    const express = require('express')
    const app = express()
    const router = express.Router()
    
    // simple logger for this router's requests
    // 이 라우터에 온 모든 리퀘스트는 이 미들웨어를 처음으로 떄린다.
    
    router.use((req, res, next) => {
      console.log('%s %s %s', req.method, req.url, req.path)
      next()
    })
    
    // 경로가 '/bar' 로 시작하는 것만 받는다. 
    router.use('/bar', (req, res, next) => {
      // ... maybe some additional /bar logging ...
      next()
    })
    
    // 항상 호출된다.
    router.use((req, res, next) => {
      res.send('Hello World')
    })
    
    app.use('/foo', router)
    
    app.listen(3000)

    순서

     

    미들웨어를 정의하는 순서 router.use()는 매우 중요합니다. 

    순차적으로 호출되므로 순서에 따라 미들웨어 우선 순위가 정의됩니다. 

    예를 들어, 일반적으로 로거는 가장 먼저 사용하는 미들웨어이므로 모든 요청이 기록됩니다.

    const logger = require('morgan')
    
    router.use(logger())
    router.use(express.static(path.join(__dirname, 'public')))
    router.use((req, res) => {
      res.send('Hello')
    })

     

    코드 위치에 따라 로깅 시작지점도 달라진다.

    router.use(express.static(path.join(__dirname, 'public')))
    router.use(logger())
    router.use((req, res) => {
      res.send('Hello')
    })

     

     

    https://expressjs.com/en/5x/api.html#router

     

    Express 5.x - API Reference

    Express 5.x API Note: This is early beta documentation that may be incomplete and is still under development. express() Creates an Express application. The express() function is a top-level function exported by the express module. const express = require('

    expressjs.com

     

     

     

    'JavaScript > Exress' 카테고리의 다른 글

    에러로그 : winston, morgan  (0) 2022.10.12
    express.urlenconded()  (0) 2022.10.11
    Express) app 객체, request 객체  (0) 2022.10.01
Designed by Tistory.