웹프로그래밍/node.js

익스프레스(ExpressJS) 기초

hyun_jo_o 2019. 6. 3. 16:03

익스프레스JS

익스프레스는 노드JS에서 대표적인 웹 프레임워크입니다. 

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

cmd창에 설치 : npm install express


 

어플리케이션이란?

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

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

 

미들웨어란?

  • 미들웨어는 함수들의 연속이다.
  • 404, 500 에러 미들웨어를 만들어보자

미들웨어를 추가할 때는 use()함수를 사용한다.

next()를 호출하지 않으면, logger2가 동작하지 않는다.

미들웨어의 본연의 기능을 수행한 후 next()함수를 호출하는 것은 필수이다.

 

  • 로깅 미들웨어를 만들어보자
const express = require('express');
const app = express();

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

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

app.use(logger);
app.use(logger2);

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

 

  • 써드파티 미들웨어(다른 개발자가 만든 미들웨어)를 사용해보자 (morgan 사용)

cmd 창에 설치 : npm install morgan

const morgan = require('morgan');

app.use(morgan('dev'));

 

https://www.npmjs.com/package/morgan

 

  • 일반 미들웨어 vs 에러 미들웨어
const express = require('express');
const app = express();

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

function errormw(err, req, res, next) {		// 에러 미들웨어
	console.log(err.message);
    // 에러를 처리하거나
    next();
}

app.use(commonmw);
app.use(errormw);

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

실행 결과

 


요청 객체

  • 클라이언트 요청 정보를 담은 객체를 요청(Request)객체라고 한다.
  • http 모듈의 request 객체를 래핑한 것이다. 더 사용하기 쉽게 만들었다.
  • req.params(), req.query(), req.body() 메소드를 주로 사용한다.

응답 객체

  • 클라이언트 응답 정보를 담은 객체를 응답(Response)객체라고 한다.
  • http 모듈의 response 객체를 래핑한 것이다. 더 사용하기 쉽게 만들었다.
  • res.send(), res.status(), res.json() 메소드를 주로 사용한다.

 

 

expressJS 참고 :

http://expressjs.com/