반응형
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
- 월별 운동일지
- wecode
- MySQL
- 크로스핏
- 습윤밴드
- github
- JavaScript
- 위코드
- 달리기
- SQL
- Til
- node.js
- dml
- Udemy
- node
- 박스점프
- 운동일지
- 러닝
- 홈트
- git
- 활동 킬로칼로리
- 드림코딩
- 독서 리뷰
- 메디패치
- dql
- axios
- code kata
- express
- 걷기
- nodejs
Archives
- Today
- Total
RISK IT
[TIL4_23.1.12.] Simple API - 게시글 등록, 목록조회 및 httpie 입력방법 본문
반응형
이 번 글은assignment 2
: 게시글 등록하기
assignment 3
: 게시글 목록 조회하기
두 개 진행한 소스코드이다.
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");
const server = http.createServer();
const httpRequestListener = function (request, response) {
const { url, method } = request;
if (method === "GET") {
if (url === "/lists") {
const data = [];
for (let i = 0; i < users.length; i++) {
for (let j = 0; j < posts.length; j++) {
if (users[i].id === posts[j].userId) {
let userPost = {
userID: users[i].id,
userName: users[i].name,
postingID: posts[j].id,
postingTitle: posts[j].title,
postingContent: posts[j].content,
//기존에 있는 users, posts 정보 사용
};
data.push(userPost);
}
}
}
console.log(data);
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
JSON.stringify({
//객체를 JSON 문자열 형태로 변환
data: data,
})
);
}
}
if (method === "POST") {
if (url === "/users/signup") {
let body = "";
request.on("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.end(
JSON.stringify({
message: "userCreated",
users: users,
})
);
});
} else if (url === "/posts") {
let body = "";
request.on("data", (data) => {
body += data;
});
request.on("end", () => {
const post = JSON.parse(body);
posts.push({
id: post.id,
title: post.title,
content: post.content,
userId: post.userId,
});
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
JSON.stringify({
message: "postCreated",
posts: posts,
})
);
});
}
}
};
server.on("request", 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}`);
});
/*
NOTE 유저 정보 테스트 입력 값
http -v POST 127.0.0.1:8000/users/signup id:=3 name="김테스트" email="test@gmail.com" password="test_password"
*/
/*
NOTE 게시물 생성 테스트 입력 값
http -v POST 127.0.0.1:8000/posts id:=3 title="테스트 타이틀" content="테스트 내용" userId:=2
*/
/*
NOTE 게시글 목록 테스트 입력 값
http -v GET 127.0.0.1:8000/lists
*/
httpie 입력 방법
내가 터미널에 입력했던 httpie 사용방법에 대해 분석해보자(맨 밑 주석 처리한 부분)
// 입력 예시
http -v POST 127.0.0.1:8000/users/signup id:=3 name="김테스트" email="test@gmail.com" password="test_password"
httpie 기본 시놉시스
http [flags] [METHOD] URL [ITEM [ITEM]]
http
기본입력
-v
Output options
옵션: -v
, --verbose
verbose는 '말수가 많은' 이란 뜻이다.
프린트 되는 내용: Print the whole HTTP exchange (request and response). 즉, request와 response의 전체 HTTP 변화에 대한 내용을 출력한다
--verbose
는 요청을 디버깅하거나 문서를 생성할 때 유용하게 사용할 수 있다.
POST
[METHOD]에 해당하는 부분
GET이나 POST를 사용할 수 있다.
127.0.0.1:8000/users/signup
입력하는 url 주소
id:=3 name="김테스트" email="test@gmail.com" password="test\_password"
[ITEM]에 해당하는 부분
반응형
'IT > TIL' 카테고리의 다른 글
[TIL6_23.1.14.] mySQL 데이터 추가/수정/삭제/조회 (0) | 2023.01.14 |
---|---|
[TIL5_23.1.13.] mySQL - DDL 이용하여 데이터베이스 생성, 접근, 변경 (0) | 2023.01.14 |
[TIL3_23.1.11] Simple API - 유저 회원가입 하기 (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 |