본문 바로가기
Web/Node.js

express module - request, response 객체

by juein 2018. 3. 6.

express module

http 모듈에 여러 기능을 추가해 쉽게 사용할 수 있게 만들어진 모듈로, 웹 서버 구축시 가장 많이 사용한다.

express 프레임워크에서 많이 다루게 된다.


express 모듈 설치

npm install express




[미들웨어 개요]

http 모듈과 express 모듈의 차이점으로, express 모듈은 request 이벤트 리스너를 연결하는데 use() 메서드를 사용한다는 것이다.

use()메서드는 여러번 사용할 수 있고, function(request, response, next) {} 형태의 함수에서 

매개변수 next 는 다음 위치에 함수를 의미한다.


미들웨어 사용 예

//모듈 추출
var express = require('express');

var hostname = 'localhost';
var port = 3000;

//express() 함수로 서버 생성
var app = express();

//미들웨어 설정 1
app.use(function(req, res, next){
    console.log('첫번째 미들웨어');
    next();
});

//미들웨어 설정 2
app.use(function(req, res, next){
    console.log('두번째 미들웨어');
    next();
});

//미들웨어 설정 3
app.use(function(req, res, next){
    console.log('세번째 미들웨어');
    
    //응답
    res.writeHead(200, {
        'Content-Type' : 'text/html'
    });
    res.end('

express test page

'); }); //서버 실행 app.listen(port, function(){ console.log('Server running at http://'+hostname+':'+port); })

위 코드를 실행하면 웹 페이지에는 'express test page' 텍스트만 보이지만

터미널 실행 창을 보면 미들웨어 첫번째, 두번째, 세번째 순서대로 실행 된게 보인다.

미들웨어에 대한 사용예제는 따로 분리해서 적어두겠음.



express모듈에서 response, request 객체에 메서드와 속성이 추가된 부분들이 있다.


[response 객체의 메서드]

response.send( [body] ) : 매개변수 자료형에 따른 형태로 응답(문자열 : html, 배열 : json, 객체 : json)

response.json( [body] ) : json 형태로 응답

response.jsonp( [body] ) : jsonp 형태로 응답

response.redirect( [status], path ) : 웹 페이지 경로 강제이동


send() 메서드 사용예제

//모듈 추출
var express = require('express');

var hostname = 'localhost';
var port = 3000;

//express() 함수로 서버 생성
var app = express();

app.use(function(req, res){

    //데이터 생성
    var test = [];
    for (var i = 0; i <= 2; i ++){
        test.push({
            idx : i,
            title : 'title_' + i
        });
    }

    //send()로 응답
    res.send(test);
});

//서버 실행
app.listen(port, function(){
    console.log('Server running at http://'+hostname+':'+port);
})

response.send() 로 객체 데이터를 넘겼으므로 JSON 형식으로 출력된다.

↓ 요런 식으로 출력



[request 객체의 메서드]

params : 라우팅 매개변수 추출

query : 요청 매개변수 추출

headers : 요청 헤더 추출

header() : 요청 헤더의 속성을 지정, 또는 추출

accepts(type) : 요청 헤더의 accept 속성 확인

is(type) : 요청 헤더의 Content-Type 속성 확인



header() 메서드로 요청 헤더(user-agent 속성 추출)

//미들웨어 설정
app.use(function (req, res, next)){
    
    //user-agent 속성 추출
    var agent = req.header('User-Agent');

    //브라우저 구분 후 응답
    if(agent.toLowerCase().match(/chrome/)){
        res.send('

크롬 브라우저로 접속~

'); }else { res.send('

기타 브라우저로 접속~

'); } });

query 속성을 사용하여 요청 매개변수 추출 

//미들웨어 설정
app.use(function (req, res, next){

    var page = request.query.page;
    var category = request.query.category;

    //응답
    res.send('

page : '+ page +', category : '+ category +'

'); // http://127.0.0.1?page=1&category=test 로 접속시 page : 1, category : test 로 출력 });


'Web > Node.js' 카테고리의 다른 글

mysql module  (0) 2018.03.12
express moduler  (0) 2018.03.07
http module (server, request, response, cookie)  (0) 2018.03.02
Node js Email Send  (0) 2018.03.02
gulp-less  (0) 2018.03.01

댓글