■ Front-End ■/Node.js

[Node.js] http 모듈로 웹으로 GET/POST를 서비스해보자.

한길(One Way) 2023. 2. 26.
Node.js는 빠르고 쉬우며 확장 가능한 JavaScript 런타임이다.

 

1. 개요

Node.js에서 http 모듈로 웹으로 GET/POST를 서비스해 보는 예제이다.

2. 사용법

http 모듈과 fs 모듈을 선언한다.

        var http = require('http'); 
        var fs = require('fs');

 

요청에 대한 onRequest() 함수를 생성한다. 콜백함수의 파라미터로 request와 response를 받는다.

        function onRequest(request, response) {
                …(중략)… 
        }

 

http 객체에 createServer() 함수로 Server를 생성하면서 콜백함수로 onRequest를 지정해 준다.

        http.createServer(onRequest).listen(1337, function() {
                console.log('http://127.0.0.1:1337');
        });

요청 Method에 따라 GET인 경우는 html 파일을 전송해 주고 POST인 경우는 파라미터 정보를 표시해 준다.

        if (request.method == 'GET') {
                fs.readFile('http-page.html', function(error, data) {
                        response.end(data);
                });
        }
        else if (request.method == 'POST') {
                …(중략)…
        }

 

3. 예제

서버 전체 코드이다.

/** GET/POST */
 
var http = require('http');
var fs = require('fs');
 
function onRequest(request, response) {
 
  response.writeHead(200, { 'Content-Type' : 'text/html' });
  
  if (request.method == 'GET')
  {
     fs.readFile('hello-page.html', function(error, data) {
       response.end(data);
     });
  }
  else if (request.method == 'POST')
  {
     request.on('data', function(data) {
       param = data.toString();
       console.log("param = " + JSON.stringify(param));
      
       params = param.split('&');
       console.log("params = " + params);
      
       response.writeHead(200, { 'Content-Type' : 'text/html' });
       for ( var i = 0; i < params.length; i++)
       {
         var vals= params[i].split('=');
         response.write('<h3>' + vals[0] + ' = ' + vals[1] + '</h3>');
       }
       response.write('<hr>');
       response.write('<footer style="text-align: center;">');
       response.write('  <a href="http://blog.naver.com/agapeuni">" target="_blank" class="con_link"></a>">">http://blog.naver.com/agapeuni');
       response.write('</footer>');       
       response.end();
     });
  }
}
 
http.createServer(onRequest).listen(1337, function() {
  console.log('http://127.0.0.1:1337');
});
 

 

아래는 GET 요청에 대한 hello-page.html 파일이다.

<!DOCTYPE html>
<html>
<head>
<title>Node.js Example</title>
</head>
<body>
  <fieldset>
     <legend>Send Data</legend>
     <form method="post">
       <table>
         <tr>
           <td><label>name</label></td>
           <td><input type="text" name="name" value="Node" /></td>
         </tr>
         <tr>
           <td><label>version</label></td>
           <td><input type="text" name="version" value="v0.12.2" /></td>
         </tr>
       </table>
       <input type="submit" />
     </form>
  </fieldset>
  <hr>
  <footer style="text-align: center;">
     <a href="http://blog.naver.com/agapeuni">http://blog.naver.com/agapeuni</a>
  </footer>
</body>
</html>
 

 

실행 결과

크롬 브라우저에서 http://127.0.0.1:1337 요청 시 표시되는 첫 화면이다.

 

name 과 version에 값을 입력하고 제출 버튼을 클릭하면 POST 요청이 되고 아래와 같이 표시된다.

 

 

728x90

댓글