본문 바로가기
WEB/Nodejs

[Nodejs] POST 데이터 가져오기 - createServer

by Ellen571 2020. 8. 4.

[생활코딩] App - POST 방식으로 전송된 데이터 받기

 

 

var http = require('http');
var qs = require('querystring');

var app = http.createServer(function(request, response){
// createServer는 nodejs로 웹브라우저가 접속이 들어올 때마다 callback함수를 호출
// callback함수의 인자 request와 response
// request는 요청할 때 웹브라우저가 보낸 정보
// response는 응답할 때 웹브라우저한테 보낼 정보

	if(pathname === '/create_process'){
		var body = '';    
    
    		request.on('data', function(data){
        	// 요청(request)이 들어오면 웹브라우저가 post로 데이터를 전송할 때
        	// 데이터를 조각내어 'data'에 담아 callback함수의 인자로 전달

			body = body + data;    // 조각된 정보를 body에 저장
		});
        
        	request.on('end', function(){
        	// 더이상 들어올 정보가 없으면 end 다음의 callback함수를 실행
        
        		var post = qs.parse(body);
            		// querystring모듈의 parse함수 인자로 데이터(body)를 넣어 post로 저장
            
            		console.log(post);
                    	console.log(post.title);
        	});
    	}
});

 

[결과]

console.log(post) -> { title: '제목입니다', description: '내용입니다' }

- request.on 과 response.on의 콜백함수를 통해 정보를 객체화하고 출력할 수 있음

console.log(post.title) -> 제목입니다

반응형