ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 제로부터 시작하는 Node.js - 7. http 모듈 2편 (Cookie, Request, Page)
    내가 보기 위해 쓰는 것/Node.js 2019. 11. 5. 15:10

    1. 쿠키

    1-1. 쿠키의 정의

    쿠키란 '일정 기간' 저장되는 데이터입니다. 활용도는 다양합니다, 로그인 상태 유지 등...

    쿠키에는 키와 값이 들어있으며 이름, 값, 파기날짜, 경로 정보등이 기록되어있습니다. 쿠키는 서버와 클라이언트 모두 저장하고 사용할 수 있습니다.

     

    1-2. 쿠키 생성

    response 객체를 사용하여 쿠키를 할당할 수 있습니다. 이때는 응답헤더를 Set-Cookie속성으로 사용합니다. Set-Cookie 속성에는 아래처럼 문자열 형태로 이루어진 쿠키의 배열을 입력해야합니다.

    Name = Value; Expires = 날짜; Domain = 도메인; Path = 경로; Secure

    우선 간단한 예제입니다.

     

    const http = require('http')
    
    http.createServer(function (req, res) {
    
      // 쿠키의 유효기간 (Exoires 속성) 변수입니다.
      let date = new Date()
      date.setDate(date.getDate() + 7)
    
      // 쿠키를 입력합니다.
      res.writeHead(200, {
        'Content-Type': 'text/html',
        'Set-Cookie': [
          'myname = seongsoo; Expires = ' + date.toUTCString(), // myName에 유효기간설정
          'mygoal = good developer'
        ]
      })
      res.end('<h1>' + req.headers.cookie + '</h1>')
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })

    첫 접속에는 아무것도 안뜨지만...
    두 번째 접속에서는 쿠키를 보여준다.
    크롬은 F12를 눌러 개발자도구에서 Application 탭에서 쿠키정보를 볼 수 있다.

     

    만드는 법은 알았으니 활용도 해봐야겠죠.

    쿠키에 따라서 다르게 응답하는 예제입니다. 여기서는 모듈 Cookie를 사용하겠습니다.

     

    cookie 모듈은 패키지매니저를 통해 설치해줘야 사용할 수 있습니다.

    https://www.npmjs.com/package/cookie

     

    cookie

    HTTP server cookie parsing and serialization

    www.npmjs.com

    터미널을 열고 설치부터 한후 예제를 작성해야 합니다.

    (어차피 Express를 사용하게 될 것이니 중요하진 않습니다.)

    npm install cookie
    const http = require('http')
    const cookie = require('cookie')
    
    http.createServer(function (req, res) {
    
      res.writeHead(200)
      let cookies = {}
      if(req.headers.cookie !== undefined){
        cookies = cookie.parse(req.headers.cookie)
      } else {
        console.log('no cookie')
      }
      
      res.end('<h1>Hello! ' + cookies.myname + '</h1>')
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    

     

     

    2. 페이지 강제 이동

    클라이언트가 요청했을 때, 특정 조건에 따라 페이지를 강제 이동해야하는 경우가 있습니다.

    바로 예제부터 살펴보겠습니다.

     

    const http = require('http')
    
    http.createServer(function (req, res) {
    
      res.writeHead(302, { 'Location': 'https://www.naver.com' })
      res.end()
      
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    

     

    접속하면 네이버에 들어가질겁니다.

    예제처럼 Location 속성에 웹페이지 주소를 입력하면 됩니다.

     

    잘보면 WriteHead메서드 첫 번째 매개변수에 200이 아닌 다른 숫자가 있습니다. writeHead의 첫 번째 매개변수는 Status Code라고 합니다. 코드 302는 이렇게 강제 페이지 이동을 할 때 자주 쓰이는 코드입니다. Status Code는 너무 많아 전부 설명할 순 없습니다만 대략적으로 정리해보았습니다.

     

    HTTP Status Code 설명
    1?? 처리 중 100 Continue
    2?? 성공 200 OK
    3?? 리다이렉트 300 Mutiple Choices
    4?? 클라이언트 오류 400 Bad Request
    5?? 서버 오류 500 Internal Server Error

     

     

    예를들어 404 Page Not Found 메시지는 서핑하면서 한 번쯤 보셨을 겁니다.

    writeHead메서드 첫번째 매개변수로 404를 입력하면 404에러를 발생시킬 수 있습니다.

     

    이런거요

    3. request 객체

    3-1. request 객체의 속성

    속성 설명
    method 클라이언트의 요청방식
    url 클라이언트가 요청한 URL을 나타냅니다.
    headers 요청 메시지 헤더를 나타냅니다.
    trailers 요청 메시지 트레일러를 나타냅니다.
    httpVersion http 프로토콜 버전을 나타냅니다.

    이번에는 이 속성들을 사용해서 요청페이지 제공, 페이지 구분 등 여러가지 기능을 살펴보겠습니다.

     

    url 속성을 이용하여 페이지를 구분하는 예제입니다.

     

    파일구성입니다.

     

     

    server.js 입니다.

    const http = require('http')
    const fs = require('fs')
    const url = require('url')
    
    http.createServer(function (req, res) {
    
      // URL을 받아올 변수를 선언합니다.
      let path = url.parse(req.url).pathname
    
      // 페이지를 구분합니다.
      if (path == '/') {
    
        // index.html로 응답합니다.
        fs.readFile('./index.html', function (err, data) {
          res.writeHead(200, { 'Content-Type': 'text/html' })
          res.end(data)
        })
    
      } else if (path == '/otherPage') {
    
        // otherPage.html로 응답합니다.
        fs.readFile('./otherPage.html', function (err, data) {
          res.writeHead(200, { 'Content-Type': 'text/html' })
          res.end(data)
        })
    
      }
    
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    

     

    index.html 입니다.

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>main Page</title>
    </head>
    <body>
      <h1>메인 페이지 입니다</h1>
      <a href="/otherPage">다른 페이지로 갈까요?</a>
    </body>
    </html>

    otherPage.html 입니다.

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>서브</title>
    </head>
    <body>
      <h2>서브 페이지 입니다.</h2>
      <a href="/">메인 페이지로 갈까요?</a>
    </body>
    </html>

    결과를 볼까요?

     

    접속시
    링크를 타고 이동하면!

     

    3-2. method 속성을 사용하여 페이지 구분하기

    url로 페이지 구분을 하는 법은 알았지만 GET, POST 등 요청 방식에 따라 다른 페이지를 제공하는 것도 알아야 합니다.

    request 객체의 method 속성으로 요청방식을 구분해봅시다.

     

    server.js 입니다.

    const http = require('http')
    const fs = require('fs')
    
    http.createServer(function (req, res) {
    
      if (req.method == 'GET') {
        console.log('GET 요청입니다.')
      } else if (req.method = 'POST') {
        console.log('POST 요청입니다.')
      }
      
      fs.readFile('./index.html', function (err, data) {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.end(data)
      })
    
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    

     

    index.html 입니다.

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>main Page</title>
    </head>
    <body>
      <h1>페이지 입니다</h1>
      <form method="post">
        <input type="submit" value="POST방식 요청을 보냅니다." />
      </form>
      <form method="get">
        <input type="submit" value="GET방식 요청을 보냅니다." />
      </form>
    </body>
    </html>

    접속해서 버튼을 누르면 console.log 메시지가 나옵니다.

     

    3-3. GET, POST 요청값 추출하기

    이제 GET, POST 요청이 온 값을 가져오는 방법을 알아보겠습니다.

    마찬가지로 예제를 보면서 이해하는 것으로 하겠습니다.

     

    3-3-1. GET 방식 값 추출하기

    server.js 입니다.

     

    const http = require('http')
    const url = require('url')
    const fs = require('fs')
    
    http.createServer(function (req, res) {
    
      let path = url.parse(req.url).pathname
      let query = url.parse(req.url, true).query
    
      if (path === '/') {
        fs.readFile('./index.html', function (err, data) {
          res.writeHead(200, { 'Content-Type': 'text/html' })
          res.end(data)
        })
      } else if (path === '/show') {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.end('<h1>' + JSON.stringify(query) + '</h1>')
      }
    
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    

     

    index.html 입니다.

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>main Page</title>
    </head>
    <body>
      <h1>GET 페이지 입니다</h1>
      <form method="get" action="/show">
        <input type="text" name="yourName" />
        <input type="password" name="passwords">
        <input type="submit" value="GET 방식 요청을 보냅니다." />
      </form>
    </body>
    </html>
    

     

    값을 입력하고 요청을 보내면...

     

    get 방식으로 받은 값을 JSON 형식으로 보여줍니다.

     

    query 메소드를 통해서 url의 query를 추출해 JSON으로 추출하는 방법이었습니다.

     

    3-3-2. POST 방식 값 추출하기

    눈치채셨을 수도 있고 이미 아실수도 있지만, 여기서 GET 방식과 POST 방식의 차이를 먼저 언급할까 합니다.

    위 예제로 GET방식을 통해 패스워드 속성의 값을 전송해봤습니다. 저희가 알아야 할 것은 입력된 정보가 그대로 노출된다는 것입니다. GET방식은 노출된 방식입니다. POST방식은 데이터를 노출하지 않고 더 많이 전송할 수 있습니다.

    그러니까 POST 방식은 query에 노출되지 않기 때문에 다른 방식으로 값을 추출해야합니다.

     

    간단하게 위 예제를 수정해서 먼저 맛을 보겠습니다.

     

    const http = require('http')
    const url = require('url')
    const fs = require('fs')
    
    http.createServer(function (req, res) {
    
      let path = url.parse(req.url).pathname
    
      if (path === '/') {
        fs.readFile('./index.html', function (err, data) {
          res.writeHead(200, { 'Content-Type': 'text/html' })
          res.end(data)
        })
      } else if (path === '/show') {
        req.on('data', function (data) {
          res.writeHead(200, { 'Content-Type': 'text/html' })
          res.end('<h2>' + data + '</h2>')
        })
      }
    
    }).listen(3001, function () {
      console.log('Server is Running at http://127.0.0.1:3001')
    })
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>main Page</title>
    </head>
    <body>
      <h1>POST 페이지 입니다</h1>
      <form method="post" action="/show">
        <input type="text" name="yourName" />
        <input type="text" name="passwords">
        <input type="submit" value="POST방식 요청을 보냅니다." />
      </form>
    </body>
    </html>

    POST방식으로 받은 값은 query를 통해 노출되지 않습니다.

    POST방식으로 받은 값은 request 이벤트 발생후 'data' 라는 이름의 이벤트로 받게 됩니다.

    잘 보시면 on메소드를 통해 'data' 이벤트를 등록하여 매개변수로 데이터를 받은 것을 확인할 수 있습니다.

     

    이 글은 여기까지 입니다. 다음 글은 외부 모듈에 대해서 알아보겠습니다.

    댓글

Designed by Tistory.