HTTP는 자바스크립트에서 HTTP 서버 빛 클라이언트 응용 프로그램을 만드는 데 사용할 수 있는 Node.js모듈이다. HTTP 내장 모듈을 사용하면, Node.js가 HTTP를 통해 데이터를 전송할 수 있다.
🔵 createServer()
메서드를 사용하여 HTTP 서버를 만든다.
const http = require('http');
//create a server object:
const server = http.createServer((req, res) => {
req.on('data', (chunk)=>{
console.log(chunk)
}).on('end', ()=>{
res.writeHead(201, {'Content-Type' : 'text/plain'})
})
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.write('Hello there'); //write a response to the client
res.write(req.url);
res.end(); //end the response
})
.listen(8080); //the server object listens on port 8080
console.log('server running on port 8080');
🔵 const http = require('http');
가장 먼저, HTTP 모듈을 포함해야 한다.
🔵 http.createServer((req, res) => {
createServer()메서드를 사용하여 웹 어플리케이션을 만들 수 있다. 이 메서드는 두개의 파라미터를 받는다.(request, response)
- request는 요청을 담당하는데, 서버로 보내는 요청에 대한 정보가 들어있다.(localhost:8000 이라고 친 행위도 서버에 그 주소에 해당하는 정보를 달라고 요청한 것이다.) request에 대한 처리 결과를 response 객체로 돌려준다.
- response는 클라이언트(브라우저)로 돌려줄 응답이다. 어떤 정보를 보내고 싶다면 response객체를 활용하면 된다.(페이지를 보내도 되고 JSON, AJAX나 이미지와 같은 정보를 보내도 된다.)
- request -> 서버 처리 -> response
- request와 response에는 header와 body가 있다.
header : req, rep 정보(종류, 크기, 캐시여부 등)
body : 주고 받고자 하는 내용
🔵 req.on('data', (chunk)=>{})
http 오브젝트의 createServer() 메서드를 호출한 객체에는 다양한 이벤트가 있으며, 그 처리를 통합하는 방법도 있다. 'on()'메소드는 지정된 이벤트 처리를 통합하는 것으로, 첫 번째 인수에 이벤트 이름을, 두 번째 인수에는 통합 처리(함수)를 할당한다.
🔵 res.writeHead(200, {'Content-Type': 'text/plain'});
- writeHead()메서드를 사용하여 응답의 헤더를 작성할 수 있다. 상태코드와 컨텐츠 타입을 지정할 수 있다.
- 메서더의 첫 번째 인수는 res.writeHead()의 상태코드이고(200은 모두 정상임을 의미), 두 번째 인수는 응답 헤더를 포함하는 객체이다.
🔵 res.write('Hello there');
응답에 대한 데이터를 작성할 수 있다.
🔵 res.write(req.url);
전달된 함수에는 클라이언트의 요청 http.createServer() 나타내는 req인수가 개체(http.IncomingMessage 개체)로 있다. 이 객체에는 도메인 이름 뒤에 오는 URL 부분을 포함하는 "url"속성이 있다.
🔵 res.end()
내용 내보내기가 완료되면 마지막으로 res.end()를 호쿨하여 콘텐츠 출력을 완료한다. 여기서 'end'를 호출하고 있지만, 인수로 내보낼 내용의 값을 지정하여 클라이언트에게 응답을 보낼 수 있다.
🔵 server.listen(8080)
http.Server객체가 준비되면, 'listen()'메소드를 실행한다. 그러면 서버는 대기 상태가 되고, 클라이언트에서 요청이 있으면 그것을 받아 처리할 수 있다. 인수는 포트 번호를 넣어준다. 두 번째 인수로 호스트 이름을 지정하거나, 세번째 인수에 백 로그를, 네 번째 인수에 콜백함수를 지정할 수 있지만, 첫 번째 인수가 '포트번호'임을 기억하면 된다.
예시)
class App {
init() {
console.log(this.toUpperCase.bind(this))
document
.querySelector('#to-upper-case')
.addEventListener('click', this.toUpperCase.bind(this));
document
.querySelector('#to-lower-case')
.addEventListener('click', this.toLowerCase.bind(this));
}
post(path, body) {
fetch(`http://localhost:4999/${path}`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(res => {
this.render(res);
});
}
toLowerCase() {
const text = document.querySelector('.input-text').value;
console.log(text)
this.post('lower', text);
}
toUpperCase() {
const text = document.querySelector('.input-text').value;
console.log(text)
this.post('upper', text);
}
render(response) {
const resultWrapper = document.querySelector('#response-wrapper');
document.querySelector('.input-text').value = '';
resultWrapper.innerHTML = response;
}
}
const app = new App();
app.init();
const http = require('http');
const PORT = 4999;
const ip = 'localhost';
console.log(http)
const server = http.createServer((request, response) => {
if(request.method === 'OPTIONS'){
response.writeHead(200, defaultCorsHeader);
response.end('hello mini-server sprints');
}
if(request.method === 'POST' && request.url === '/upper'){
let body = [];
request.on('data', (chunk)=>{
body.push(chunk);
}).on('end', ()=>{
body = Buffer.concat(body).toString();
response.writeHead(201, defaultCorsHeader);
response.end(body.toUpperCase());
})
}
else if(request.method === 'POST' && request.url === '/lower'){
let body = [];
request.on('data', (chunk)=>{
body.push(chunk);
}).on('end', ()=>{
body = Buffer.concat(body).toString();
response.writeHead(201, defaultCorsHeader);
response.end(body.toLowerCase());
})
}
else{
response.statusCode = 404;
response.end();
}
console.log(
`http request method is ${request.method}, url is ${request.url}`
);
});
server.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Max-Age': 10
};
<참고자료>
https://zetcode.com/javascript/http/
Node HTTP - creating HTTP server and client apps in JavaScript with HTTP module
Node HTTP tutorial last modified October 18, 2021 Node HTTP tutorial shows how to create HTTP server and client applications in JavaScript with HTTP module. HTTP HTTP is a Node.js module which can be used to create HTTP server and client applications in Ja
zetcode.com
https://www.w3schools.com/nodejs/nodejs_http.asp
Node.js HTTP Module
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/#http
HTTP 트랜잭션 해부 | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org