내가 오늘 mini node server를 만든 것은
그동안 개념으로 공부했던 클라이언트와 요청과 응답을 주고받는 서버를 만든 것
이때 요청과 응답 메세지를 주고 받는 프로토콜(통신 규약)이 HTTP이다.
= HTTP Messages
Node.js HTTP 공식문서를 보고 정리한 글입니다.
http.createServer([options][, requestListener])
options: object
requestListner: function
Returns: http.Server
Returns a new instance of
http.Server
.
TherequestListener
is a function which is automatically added to the 'request' event.
const http = require('node:http');
// Create a local server to receive data from
const server = http.createServer((req, res) => {
...
}
nodeEventTarget.on(type, listener[, options])
type: string
listener: Function
options: Object
Returns: EventTarget this
The on method binds an event to a object.
Node.js-specific alias foreventTarget.addListener()
.
on
이 어디서 온 건가 궁금했는데 node의 Class: NodeEventTarget
method였다.
https://stackoverflow.com/questions/12892717/in-node-js-request-on-what-is-it-this-on
https://nodejs.org/api/events.html#nodeeventtargetontype-listener-options
const { method, url } = request;
request 객체는 IncomingMessage의 인스턴스입니다.
An IncomingMessage object is created by
http.Server
orhttp.ClientRequest
and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers, and data.
node 내장 기능으로 request 객체가 자동 생성되므로
request.method
request.host
request.protocol
등 사용 가능하다.
request.end([data[, encoding]][, callback])
data: string | Buffer
encoding: string
callback: function
Returns: this
Finishes sending the request.
response.writeHead(statusCode[, statusMessage][, headers])
statusCode: number
StatusMessage: string
headers: object | Array
Returns: http.ServerResponse
Sends a response header to the request.
Optionally one can give a human-readablestatusMessage
as the second argument.
Returns a reference to the
ServerResponse
, so that calls can be chained.
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
This method must only be called once on a message and it must be called before
response.end()
is called.
Ifresponse.write()
orresponse.end()
are called before calling this, the implicit/mutable headers will be calculated and call this function.
response.end([data[, encoding]][, callback])
data: string | Buffer
encoding: string
callback: function
Returns: this
MUST be called on each response.
If data is specified, it is similar in effect to calling
response.write(data, encoding)
followed byresponse.end(callback)
.
If callback is specified, it will be called when the response stream is finished.
이 메소드는 모든 응답 헤더와 본문이 전송되었음을 서버에 알립니다.
실제 코드 값을 end( ) 함수로 전달하면 브라우저는 해당 컨텐츠를 받은 후 html 형태로 화면에 출력해 줍니다.
request.on('data', (chunk) => {
body.push(chunk);
})
data
를 스트림으로 받아온 뒤
body 배열에 chunk를 push한다
chunk: data를 잘게 쪼갠 단위(덩어리)
http.createServer() : 웹 서버 객체 생성자
const server = http.creatServer((request, response) => {
//
})
이후 요청을 실제로 처리하려면 listen 메서드가 server 객체에서 호출되어야 한다.
server.listen( ... )
Same-Origin Policy 원칙
http://localhost:3000/lower
http://localhost:3000/upper
---> Same-Origin
http://localhost:3000
http://localhost:4000/upper
---> port가 달라서 Same-Origin이 아니다.
protocol, host, port 가 같아야 Same-Origin이다.
preflight request: 실제 요청을 보내기 전에 OPTIONS method를 사용해서 접근 권한을 확인한다.