프로그래밍/Node.js

Node.js) Express 미들웨어2 (morgan)

이불이! 2019. 4. 26. 00:09
728x90

아래 콘솔에 나오는 GET ~ 같은 로그는 모두 morgan 미들웨어에서 나타나는 것이다.

즉, 요청에 대한 정보를 콘솔에 기록해준다. 

GET / 200 51.257 ms - 1539의 의미는

http요청(GET) - 주소(/) - http상태코드(200) - 응답속도(51.267ms) - 응답바이트(1539)

//logger 추가
const express = require('express') ;
const logger = require('morgan') ;
 
 
const app = express() ;
 
app.use(logger('dev')) ;
//const logger = () => (req, res, next) => {
//    next() ;
//} 이렇게 안에 next가 내장되어 있어서 자동으로 넘어간다.
 
    console.log('첫번째 미들웨어') ;
    next() ;
}) ;
 
    console.log('두번째 미들웨어') ;
    next() ;
}) ;
 
app.get('/', (req, res) => {
    console.log('세번째 미들웨어') ;
    res.send('Hello express') ;
}) ;
 
app.get('/users', (req, res) => {
    console.log('네번째 미들웨어') ;
    res.send('Hello users') ;
}) ;
 
//왜 마지막 미들웨어에서는 next를 안붙여도 되는걸까?
 
app.post('/', (req, res) => {
}) ;
 
app.delete('/users', (req, res) => {
}) ;
 
 
//use와 나머지 get,post...(라우팅 미들웨어)등의 차이는 use는 모든 요청을 다 받지만,
//나머지는 주소와 일치하는 요청만 걸러받는다.
module.exports = app ;
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5; text-decoration:none">Colored by Color Scripter
 

 

1. http://localhost:3000일 경우

 

2. http://loccalhost:3030/users 일 경우

 

** use를 사용한 것과 GET의 라우팅 미들웨어를 사용한 것의 차이점을 알 수 있다.@~

use까지는 공통 미들웨어라 다 처리하는 것이고, 라우터는 요청에 따라 처리하는 거! 중요