클라이언트가 백엔드 API 서버와 통신 할 때, 엔드포인트에 접속하는 형태로 통신
각 엔드포인트는 고유의 URL 주소를 가짐, 이 주소를 통해 해당 엔드포인트에 요청 보내기 가능
// app.js
const http = require('http');
const server = http.createServer();
const httpRequestListener = function (request, response) {
const { url, method } = request // (1)
if (method === 'GET') { // (2)
if (url === '/ping') { // (3)
response.writeHead(200, {'Content-Type' : 'application/json'}); // (4)
response.end(JSON.stringify({message : 'pong'}) // (5)
}
}
};
server.on("request", httpRequestListener);
server.listen(8000, '127.0.0.1', function() {
console.log('Listening to requests on port 8000');
});
(1) 코드
request 객체에서 url와 http_method 정보를 추출하여
url, method 변수에 할당
(2), (3) 코드
어떤 http 메소드 요청
target 어디인지 판별 === target이 /ping일 경우 (4),(5) 코드 실행
(4) 코드
response message의 body에 어떤 데이터 타입을 보낼지 결정하는 header 설정
(5) 코드
response.end() 함수 호출하여 클라이언트에게 http 응답을 보냄
여기에 담겨 넘겨준 값이 응답 메세지 구조 중에 body 값에 담겨짐
결국, JSON.stringify({ meassage : 'pong' }) 은
JavaScript Object를 JSON화 해서 body에 넣어주기 위해서 사용하는 모듈
필요한 정보가 무엇인지 파악할 것
$ http -v POST 127.0.0.1:8000/user \
id:=1 \
name="홍길동" \
email="honghong@gmail.com" \
password="1q2w3e4r"
# Start Line
**POST /user HTTP/1.1**
# Header
****Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 94
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/3.0.2
# Body
{
"email": "honghong@gmail.com",
"id": 3,
"name": "홍길동",
"password": "1q2w3e4r"
}
# Status Line
HTTP/1.1 200 OK
# Header
Connection: keep-alive
Content-Length: 2
Date: Tue, 26 Apr 2022 02:32:47 GMT
Content-Type: application/json
Keep-Alive: timeout=5
# Body
{
"message": "ok!",
}
// app.js
const http = require('http'); // (1)
const server = http.createServer();
const users = [ // (2)
{
id: 1,
name: "Rebekah Johnson",
email: "Glover12345@gmail.com",
password: "123qwe",
},
{
id: 2,
name: "Fabian Predovic",
email: "Connell29@gmail.com",
password: "password",
},
]
const posts = [
{
id: 1,
title: "간단한 HTTP API 개발 시작!",
description: "Node.js에 내장되어 있는 http 모듈을 사용해서 HTTP server를 구현.",
userId: 1,
},
{
id: 2,
title: "HTTP의 특성",
description: "Request/Response와 Stateless!!",
userId: 1,
},
];
const httpRequestListener = function (request, response) {
const { url, method } = request
if (method === 'GET') {
if (url === '/ping') {
response.writeHead(200, {'Content-Type' : 'application/json'});
response.end(JSON.stringify({message : 'pong'}));
}
} else if (method === 'POST') { // (3)
if (url === '/users') {
let body = ''; // (4)
request.on('data', (data) => {body += data;}) // (5)
// stream을 전부 받아온 이후에 실행
request.on('end', () => { // (6)
const user = JSON.parse(body); //(7)
users.push({ // (8)
id : user.id,
name : user.name,
email: user.email,
password : user.password
})
response.end(JSON.stringify({message : 'ok!'}); // (9)
})
}
}
};
server.on("request", httpRequestListener);
server.listen(8000, '127.0.0.1', function() {
console.log('Listening to requests on port 8000');
});
(2)번 코드
users 라는 변수에 필요한 정보 저장
(3)번 코드
http method(POST), target(/users)정보와 if문 사용해서 엔드포인트 정의
(4), (5)번 코드
http 요청을 통해 전송된 body에 담긴 정보를 읽기
따로 온 데이터를 하나로 합쳐서 body라는 변수에 정의
(6)번 코드
(4),(5)에서 데이터를 정상적으로 받아오면 실행
(7)번 코드
JSON.parse() 활용하여 JSON 데이터를 JavaScript Object로 반환
(8)번 코드
클라이언트로부터 받은 정보를 객체 형태로 만들어서 users 배열에 push
(9)번 코드
회원가입 성공적임을 알리는 "ok!" 메세지를 응답