Post

HTTP 모듈 (3: 데이터 추출과 쿠키 추출)

데이터 추출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>Send Data With POST Method</h1>
<form method="post">
    <table>
        <tr>
            <td><label>Data A</label></td>
            <td><input type="text" name="data_a"></td>
        </tr>
        <tr>
            <td><label>Data B</label></td>
            <td><input type="text" name="data_b"></td>
        </tr>
    </table>
    <input type="submit"/>
</form>

</body>
</html>
require('http').createServer(function(request, response) {
   if (request.method == 'GET') {
       //GET 요청
       require('fs').readFile('post.html', function(error, data){
           response.writeHead(200, {'Content-Type': 'text/html'});
           response.end(data);
       });
   }else if (request.method == 'POST') {
       //POST 요청
       request.on('data', function(data){
           response.writeHead(200, {'Content-Type': 'text/html'});
           response.end('<h1>' + data + '</h1>');
       });
   }
}).listen(1016, function(){
    console.log('Server Running at localhost:1016');
});


쿠키 추출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require("http")
  .createServer(function (request, response) {
    //쿠키를 추출하고 분해합니다.
    var cookie = request.headers.cookie;
    cookie = cookie.split(";").map(function (el) {
      var el = el.split("=");
      return {
        key: el[0],
        value: el[1],
      };
    });

    //쿠키를 생성합니다.
    response.writeHead(200, {
      "Content-Type": "text/html",
      "Set-Cookie": ["name = dain", "age = 30"],
    });

    //응답합니다.
    response.end("<h1>" + JSON.stringify(cookie) + "</h1>");
  })
  .listen(1016, function () {
    console.log("Server Running at localhost:1016");
  });


This post is licensed under CC BY 4.0 by the author.