ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2020/11/13 - TIL (node.js / HTTP Module Post요청)
    Develop/Node.js 2020. 11. 14. 00:47

     

     

     

     

    node.js HTTP Module

    http 모듈은 노드에서 가장 기본적인 웹 모듈이며 http 웹 서버뿐만 아니라 클라이언트를 생성하는 것과 관련된 모든 기능을 담당하는 모듈입니다.

     

    node.js에는 http라는 내장 모듈이 있어 node.js가 HTTP를 통하여 데이터를 전송할 수 있습니다.

    • require('http') 사용
    const http = require('http');

     

     

     

    Create Server

    • 모든 웹 서버 어플리케이션은  createServer 메소드를 사용하여 서버 객체를 생성합니다.

    • 서버가 실행된 후의 동작을 콜백함수로 등록합니다. 콜백 함수 안에는 request, response가 인자로 들어갑니다.
    • listen메소드를 사용하여 포트에 연결합니다.
    const http = require('http'); // 서버를 만드는 모듈 불러옴
    http.createServer((request, response) => { // 서버 만드는 메소드
      console.log('server start!');
    }).listen(8080);

     

     

     

    Request

     

    속성

    • method : 요청된 method(GET, POST,...)에 접근
    • url : 요청된 url에 접근
    • headers : 요청 메시지 헤더

     

    createServer 메소드의 인자로 전달된 request 객체는 'data'와 'end'이벤트에 의하여 요청된 데이터에 접근할 수 있습니다.

    const http = require('http'); // 서버를 만드는 모듈 불러옴
    http.createServer((request, response) => { // 서버 만드는 메소드
      let body = [];
      request.on('data', (chunk) => {
        body.push(chunk);
      }).on('end', () => {
      body = Buffer.concat(body).toString();
      // 여기서 `body`에 전체 요청 바디가 문자열로 전환됩니다.
    });
    }).listen(8080);

     

     

    Response

    응답 메시지를 작성할 때는 response 객체를 사용하여 클라이언트에게 웹페이지를 제공합니다.

     

    메소드

    • writeHead(statusCode, object) : response header를 작성합니다.
    • end([data], [encoding]) : 응답의 본문(body)을 작성합니다.
    const http = require('http'); // 서버를 만드는 모듈 불러옴
    http.createServer((request, response) => { // 서버 만드는 메소드
      let body = [];
      request.on('data', (chunk) => {
        body.push(chunk);
      }).on('end', () => {
      body = Buffer.concat(body).toString();
      // 여기서 `body`에 전체 요청 바디가 문자열로 전환됩니다.
      response.writeHead(200, {
        'Content-Type': 'application/json',
        'X-Powered-By': 'bacon'
      });
      response.end();
    }).listen(8080);

     

     

     

    POST 처리 예제

    const http = require('http');
    
    http.createServer((request, response) => {
      if (request.method === 'POST' && request.url === '/echo') {
        let body = [];
        request.on('data', (chunk) => {
          body.push(chunk);
        }).on('end', () => {
          body = Buffer.concat(body).toString();
          response.end(body);
        });
      } else { // post접근이 아니라면 404 상태코드 반환
        response.statusCode = 404;
        response.end();
      }
    }).listen(8080);

     

     

    참고 : https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/

     

    HTTP 트랜잭션 해부 | Node.js

    Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

    nodejs.org

     

Designed by Tistory.