반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- github
- dml
- Udemy
- nodejs
- 습윤밴드
- SQL
- dql
- node
- 박스점프
- 걷기
- axios
- MySQL
- 위코드
- JavaScript
- express
- 홈트
- git
- Til
- 독서 리뷰
- 드림코딩
- 크로스핏
- node.js
- code kata
- 러닝
- 달리기
- wecode
- 운동일지
- 활동 킬로칼로리
- 메디패치
- 월별 운동일지
Archives
- Today
- Total
RISK IT
[TIL3_23.1.11] Simple API - 유저 회원가입 하기 본문
반응형
SIMPLE API
Node.js에서 제공하는 built-in 모듈인 http를 사용해서 API를 구현해봅니다.
소스코드 분석
const users = [
{
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 개발 시작!",
content: "Node.js에 내장되어 있는 http 모듈을 사용해서 HTTP server를 구현.",
userId: 1,
},
{
id: 2,
title: "HTTP의 특성",
content: "Request/Response와 Stateless!!",
userId: 1,
},
];
// 회원 정보 및 게시글 정보 입력 (하드코딩)
const http = require("http"); // 1. http 모듈 불러오기
const server = http.createServer(); // 2. 서버 객체 생성(웹 서버 생성)
const httpRequestListener = function (request, response) {
// 요청 처리를 위한 함수 생성
const { url, method } = request;
if (method === "POST") {
if (url === "/users/signup") {
let body = "";
request.on("data", (data) => { // 요청에 "data"가 있으면 ~
body += data;
});
request.on("end", () => { // 요청의 데이터가 모두 받아졌으면 ~
const user = JSON.parse(body);
users.push({
id: user.id,
name: user.name,
email: user.email,
password: user.password,
});
response.writeHead(200, { "Content-Type": "application/json" });
// response 객체의 메서드인 writeHead를 사용하여 응답 헤더를 작성
// ex) response.write('Hello World!\n'); 하면 컨텐츠 내보내기
response.end(JSON.stringify({ message: "userCreated" }));
// response 객체의 메서드인 end를 사용하여 응답 본문을 작성
// 컨텐츠 출력 완료(응답 종료)
//'JSON.stringify'는 객체를 JSON 문자열로 변환
//'JSON.parse'는 JSON 문자열을 객체로 변환
});
}
}
};
server.on("request", httpRequestListener);
// 3. 요청 처리 설정
// server 객체에는 이벤트들이 있는데, .on 메서드를 사용해서 server에 이벤트 연결.
// 여기서는 클라이언트가 요청할 때 발생하는 이벤트인 "request"를 .on을 이용해서 httpRequestListener라는 함수를 연결
const IP = "127.0.0.1";
const PORT = 8000;
server.listen(PORT, IP, function () { // 대기 시작
console.log(`Listening to request on ip ${IP} & port ${PORT}`); // 콘솔에 출력
}); // 서버 생성해서 잘 실행될 경우 콘솔로그로 찍기
// .listen은 server 객체의 메서드
});
/* NOTE 유저 정보 테스트 입력 값
http -v POST 127.0.0.1:8000/users/signup id=3, name="김테스트", email="test@gmail.com", password="test_password"
*/
// 이렇게 주석 처리 했었으나,
// -- 1. id name email password 사이의 comma는 빼고 입력해야 함
// -- 2. 숫자로 입력하려면 = 대신 != 으로 입력
반응형
'IT > TIL' 카테고리의 다른 글
[TIL6_23.1.14.] mySQL 데이터 추가/수정/삭제/조회 (0) | 2023.01.14 |
---|---|
[TIL5_23.1.13.] mySQL - DDL 이용하여 데이터베이스 생성, 접근, 변경 (0) | 2023.01.14 |
[TIL4_23.1.12.] Simple API - 게시글 등록, 목록조회 및 httpie 입력방법 (0) | 2023.01.13 |
[TIL 2_23.1.10.] built-in file system (0) | 2023.01.11 |
[TIL 1_23.1.9.] API (0) | 2023.01.09 |