[Express] request.on('end', function() { }) 란?

혜 콩·2023년 12월 5일

Backend

목록 보기
4/9

POST 요청

app.post('/create_process', function(request, response) {
  var body = '';
    request.on('data', function(data){
        body = body + data;
    });
    request.on('end', function(){
        var post = qs.parse(body);
        var title = post.title;
        var description = post.description;
        fs.writeFile(`data/${title}`, description, 'utf8', function(err){
          response.writeHead(302, {Location: `/page/${title}`});
          response.end();
        })
    });
})

request.on('data', function(data) { })❓
request.on('end', function() { }) ❓

request.on('data', callback) 은 Node.js의 HTTP 모듈에서 제공하는 이벤트 핸들러
→ HTTP 요청의 데이터 전송이 완료되었을 때 발생하는 이벤트

데이터가 여러 조각(chunk)으로 전송되며, 데이터 수신이 끝나면 request.on('end', callback) 호출

  • 여러 조각의 데이터가 전송된다면 callback 함수가 여러 번 호출됩니다. 따라서 호출될 때마다 데이터를 누적해주어야 합니다.
    • data를 누적하기 위한 변수 혹은 버퍼를 활용
var body = '';

request.on('data', function(data){
    // 각 데이터 조각을 누적
    body += data;
});

request.on('end', function(){
    // 모든 데이터 수신이 완료되면 이 부분에서 누적된 데이터를 사용하여 로직을 처리
    var post = qs.parse(body);
    var title = post.title;
    var description = post.description;

    // ...
});

body 변수는 수신된 모든 데이터를 나타내기 때문에 일반적으로 쿼리 문자열 형식

"title=MyTitle&description=MyDescription" 

qs.parse(body) 를 사용하게 되면, 아래와 같은 객체로 변환 (Key-Value)

{
  title: 'MyTitle',
  description: 'MyDescription'
}

⬇️

미들웨어를 이용하여 body에 데이터를 누적하여 더하는 방식이 아닌 body-parser를 이용하여 더 간결하게 코드 작성이 가능하다.

body-parser

npm install body-parser

var bodyparser = require('body-parser')

// form data를 받아올 때
app.use(bodyparser.urlencoded({extended: false}))
// ↑ bodyparser가 만들어내는 미들웨어

모든 데이터를 가지고 와서 body를 만들어주는 body-parser를 통해 request.body 가 생겨납니다.

app.post('/create_process', function(request, response) {
  var post = request.body
  var title = post.title;
  var description = post.description;
  fs.writeFile(`data/${title}`, description, 'utf8', function(err){
    response.redirect(`/page/${title}`)
  }) 
profile
배우고 싶은게 많은 개발자📚

0개의 댓글