Language/Node.js

[TDD기반 Node.js 공부하기] 03. ExpressJS 기초

MOMOBOB 2022. 6. 13. 01:40
반응형

익스프레스란

Express는 웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 유연한 Node.js 웹 애플리케이션 프레임워크이다.

쉽게 말해 Node.js를 이용하여 웹개발을 할 때 도움을 주는 프레임워크이다.

 

익스프레스(ExpressJS) 설치

npm install express

 

익스프레스(ExpressJS)를 제대로 알기 위한 5가지 개념

  • 어플리케이션
  • 미들웨어
  • 라우팅
  • 요척객체
  • 응답객체

 

어플리케이션

  • 익스프레스 인스턴스 객체를 의미함
  • 서버에 필요한 기능인 미들웨어를 어플리케이션에 추가할 수 있음.
  • 라우팅 설정을 할 수 있음.
  • 서버를 요청 대기 상태로 만들수 있음.
  • 익스프레스 인스턴스 생성 : 
const express = require('express');
const app = express();

app.listen(3000, function() {
	console.log('Server is running');
})

 

미들웨어

미들웨어란 함수들의 연속이다.

로깅 미들웨어 예제

const express = require('express');
const app = express();

function logger(req, res, next) {
    console.log('i am logger');
    next();
}

app.use(logger);

app.listen(3000, function() {
	console.log('Server is running');
})

 

curl localhost:3000으로 접속한 결과 : 

Server is running
i am logger

 

미들웨어 실행 순서

여러개의 미들웨어를 실행한 예제

const express = require('express');
const app = express();

function logger1(req, res, next) {
    console.log('i am logger1');
    next();
}

function logger2(req, res, next) {
    console.log('i am logger2');
    next();
}

app.use(logger1);
app.use(logger2);

app.listen(3000, function() {
	console.log('Server is running');
})

 

curl localhost:3000 실행 결과

Server is running
i am logger1
i am logger2

 

 use로 추가된 미들웨어 함수(logger1)가 먼저 실행되고 함수 마지막의 next()를 호출하여 use를 통해 두번째로 추가된 함수(logger2)를 호출한다.

 

미들웨어 함수에서 next를 호출하지 않으면 안된다. 다음 미들웨어 함수실행이 안되어 응답조차 가지 않게 됨.

 

반응형

 

써드파티 미들웨어 사용하기

써드파티 미들웨어 : 다른사람이 만든 미들웨어를 쓰겠다는 뜻.

https://www.npmjs.com 

 

npm

Bring the best of open source to you, your team, and your company Relied upon by more than 11 million developers worldwide, npm is committed to making JavaScript development elegant, productive, and safe. The free npm Registry has become the center of Java

www.npmjs.com

 

npm 사이트를 통해서 다른사람이 만든 미들웨어를 조회해보고 가이드를 통해 사용해볼 수 있다.

morgan 사용해보기

npm install morgan
const express = require('express');
const morgan = require('morgan');
const app = express();

function logger1(req, res, next) {
    console.log('i am logger1');
    next();
}

function logger2(req, res, next) {
    console.log('i am logger2');
    next();
}

app.use(logger1);
app.use(logger2);
app.use(morgan);

app.listen(3000, function() {
	console.log('Server is running');
})
Server is running
i am logger1
i am logger2
GET / 404 5.179 ms - 139

  

일반 미들웨어 vs 에러 미들웨어

const express = require('express');
const app = express();

// 일반 미들웨어åå
function commonMw(req, res, next) {
    console.log('일반 미들웨어');
    next(new Error('error ouccered'));
}

// 에러 미들웨어
function errorMw(err, req, res, next) {
    console.log('에러 미들웨어', err.message);
    // 에러를 처리후 next 호출
    next();
}

app.use(commonMw);
app.use(errorMw);

app.listen(3000, function() {
    console.log('Server is running');
})
Server is running
일반 미들웨어
에러 미들웨어 error ouccered

 

라우팅

  • 요청 url에 대해 적절한 핸들러 함수로 연결해 주는 기능
  • 어플리케이션의 get(), post() 메소드로 구현할 수 있음
  • 라우팅을 위한 전용 Router 클래스를 사용할 수도 있음

 

익스프레스 없이 라우팅 하기

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {

  if (req.url ==='/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World!\n');
  } else if (req.url === '/users') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('User List!\n');
  }
  else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

 

요청 객체

  • 클라이언트 요청 정보를 담은 객체를 요청(Request)객체라고 함
  • http 모듈의 request 객체를 래핑한 것
  • res.params(), res.query(), res.body() 등과 같은 사용하기 쉬운 함수를 제공
 

응답 객체

  • 클라이언트 응답 정보를 담은 객체를 응답(Response)객체라고 함
  • http 모듈의 response 객체를 래핑한 것
  • res.send(), res.status(), res.json() 등과 같은 사용하기 쉬운 함수를 제공

 

Express를 이용한 Hello world 예제

http://expressjs.com/ko/starter/hello-world.html

 

Express "Hello World" 예제

Hello world 예제 기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제

expressjs.com

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

 

 

끝.

 

 


Thank you!

 

 

반응형