Nodejs Module 'http'

2019. 12. 1. 02:58·Web/Nodejs

 

1. 개념

HTTP

To use the HTTP server and client one must require('http').

The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses — the user is able to stream data.

HTTP message headers are represented by an object like this:

{ 'content-length': '123', 'content-type': 'text/plain', 'connection': 'keep-alive', 'host': 'mysite.com', 'accept': '*/*' }

 

출처: Nodejs Docs

 

 

2. http  Tag

GET, POST 등 쿼리 정보는 다음 문서 참조

https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3

 

HTTP/1.1: Method Definitions

part of Hypertext Transfer Protocol -- HTTP/1.1 RFC 2616 Fielding, et al. 9 Method Definitions The set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for

www.w3.org

3. 관련 메소드

 

구조적으로 들어갈 수 밖에 없는 메소드

자주 쓰이고 중요해서 정리해둔다.

http.request

Interface http.request(options, callback)
Parameter

option: Object or String

※ if String, it's parsed by url.parse() method.

callback: Function

fuction Client request to Server
return  http.ClientRequest

<Option>

host: Domain name or Server IP Address, (Default: localhost)

hostname: 호스트명을 url.parse() 통해 파싱할 때 사용.

port: Server Port Address (Default: 80)

method: HTTP Request Function Nmae (Default: GET)

path: Request Path, (Default: /)

headers: Object that has request header.

 

[agent]

HTTP Client 요청시 사용하는 Socket pool, 

Agent Option은 소켓 풀 동작 방식을 설정함.

ex) Connection : keep-alive

사용 가능한 소켓을 기다리는 http 요청이 없을 경우 -> socket.close()

기본적으로 소켓들을 재활용하는 형태로 운영됨.

=> 명시적으로 socket.close를 해줄 필요 없어서 편해짐.

  • undefined(Defualt) : use Node.js Global Agent

  • Agent Object: Agent 내부에 존재하는 이전 소켓만 사용.

  • false: Socket Pool 사용 X, 명시적으로 'Connection: close' 로 세팅하여 매번 닫음.

 

[http 필수 Header]

  • 'Connection' : keep-alive
  • Contetn-length
  • Expect
  • Authorization
Http 필수 Header Description
Connection: keep-alive Node.js에게 서버가 커넥션을 버리지 않고 저장하여 다음 요청시 사용한다는 것을 명시
Content-length 인코딩 Default 값을 비활성화함.
Expect 요청 헤더 값들을 즉시 전달 ex. Exepct: 100-continue => Timeout , 'continue' 이벤트를 listen 하겠다는 세팅을 하게됨.
Authorization Default Authorization 대신 'auth' option 을 사용.

 

4. 예제

주석 참고하면 충분히 이해할 수 있는 수준
data를 직렬화하여 버퍼형태로 쓴다. 모든 버퍼가 비워지면 true를 반환한다.

 

[예제]

주석을 참고하자.

 

http.request의 마무리는 반드시 request.end()

 

[get 방식 요청]

Google Server에 응답 메시지를 얻어오는 구문이다.

이제 이정도는 한눈에 코드가 들어온다.

점점 nodejs가 익숙해진다.

 

 

Stream의 개념에 대해 다음 포스팅에 잘 정리되어있다.

https://github.com/FEDevelopers/tech.description/wiki/Node.js-Stream-%EB%8B%B9%EC%8B%A0%EC%9D%B4-%EC%95%8C%EC%95%84%EC%95%BC%ED%95%A0-%EB%AA%A8%EB%93%A0-%EA%B2%83

 

FEDevelopers/tech.description

기술 문서 정리하는 저장소. Contribute to FEDevelopers/tech.description development by creating an account on GitHub.

github.com

 

저작자표시 (새창열림)

'Web > Nodejs' 카테고리의 다른 글

Middleware Function 'next'  (0) 2019.12.31
express & connect  (0) 2019.12.06
node.js global 'exports'  (0) 2019.11.30
Test를 위한 모듈 'assert'  (0) 2019.11.28
module과 export  (0) 2019.11.16
'Web/Nodejs' 카테고리의 다른 글
  • Middleware Function 'next'
  • express & connect
  • node.js global 'exports'
  • Test를 위한 모듈 'assert'
M_Falcon
M_Falcon
  • M_Falcon
    Falcon
    M_Falcon
  • 전체
    오늘
    어제
    • 분류 전체보기 (432)
      • Web (16)
        • Nodejs (14)
        • Javascript (23)
        • FrontEnd (4)
      • DataBase (39)
        • Fundamental (1)
        • Redis (4)
        • PostgreSQL (10)
        • NoSQL (4)
        • MySQL (9)
        • MSSQL (3)
        • Error (4)
      • Algorithm (79)
        • Algorithm (문제풀이) (56)
        • Algorithm (이론) (23)
      • JVM (65)
        • Spring (13)
        • JPA (5)
        • Kotlin (13)
        • Java (24)
        • Error (7)
      • 기타 (70)
        • Kafka (3)
        • Kubernetes (3)
        • Docker (13)
        • git (19)
        • 잡동사니 (27)
      • 재테크 (11)
        • 세무 (4)
        • 투자 (3)
        • 보험 (0)
      • BlockChain (2)
        • BitCoin (0)
      • C (32)
        • C (10)
        • C++ (17)
        • Error (3)
      • Low Level (8)
        • OS (3)
        • 시스템 보안 (5)
      • 네트워크 (3)
      • LINUX (30)
        • Linux (26)
        • Error (4)
      • 저작권과 스마트폰의 이해 (0)
      • 생각 뭉치 (6)
      • 궁금증 (2)
      • Private (4)
        • 이직 경험 (0)
        • 꿈을 찾아서 (1)
      • Android (21)
        • OS (4)
  • 블로그 메뉴

    • 홈
    • WEB
    • 알고리즘
    • DataBase
    • Linux
    • Mobile
    • C
    • 방명록
  • 링크

    • github
  • 공지사항

  • 인기 글

  • 태그

    알고리즘
    docker
    algorithm
    java
    Programmers
    linux
    android
    Kotlin
    PostgreSQL
    Git
    백준
    kafka
    JPA
    C++
    프로그래머스
    Bitcoin
    javascript
    database
    ubuntu
    Spring
  • hELLO· Designed By정상우.v4.10.3
M_Falcon
Nodejs Module 'http'
상단으로

티스토리툴바