BE_Simple API Server_Assignment#3_10.27

송철진·2022년 10월 27일
0

Assignment#3

Assignment 2에서 만들었던 app.js 파일에 이어서 과제를 진행해주세요.

  • app.js 파일에 게시글 목록 조회 엔드포인트 구현 코드를 작성해주세요.

    • 알맞은 API 호출 URL을 설정하여서 클라이언트와(httpie/postman) 통신을 성공해주세요. 조회 요청을 보낼때는 http method 중에 GET을 사용합니다.

      		$ http -v GET 127.0.0.1:8000
    • 데이터가 호출될 때의 알맞는 http 상태코드를 반환해주세요.

    • http response로 반환하는 데이터의 형태가 다음과 같은 구조를 갖도록 만들어주세요.

      {
      	"data" : [
      	{
      	    "userID"           : 1,
      	    "userName"         : "Rebekah Johnson",
                "postingId"        : 1,
                "postingTitle"     : "간단한 HTTP API 개발 시작!",
      	    "postingContent"   : "Node.js에 내장되어 있는 http 모듈을 사용해서 HTTP server를 구현."
      	},
      	{  
      	    "userID"           : 2,
      	    "userName"         : "Fabian Predovic",
                "postingId"        : 2,
                "postingTitle"     : "HTTP의 특성",
          	    "postingContent"   : "Request/Response와 Stateless!!"
      	},
      	{  
                "userID"           : 3,
      	    "userName"         : "new user 1",
                "postingId"        : 3,
                "postingImageUrl"  : "내용 1",
      	    "postingContent"   : "sampleContent3"
      	},
      	{  
      	    "userID"           : 4,
      	    "userName"         : "new user 2",
                "postingId"        : 4,
                "postingImageUrl"  : "내용 2",
      	    "postingContent"   : "sampleContent4"
      	}
            ]
      }

1. 전체 소스코드

const http = require("http");
const server = http.createServer();
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 httpRequestListener =  function(request, response){
    const { url, method } = request;
    if (method === 'GET'){
        if (url === '/ping'){
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            response.end(JSON.stringify({message : 'pong'}));
        }else if (url === '/posts/inquire'){
            const data = [];
            for(let i = 0; i<posts.length; i++){
                for(let j = 0; j<users.length; j++){
                    if (users[j].id === posts[i].userId){
                        let userPost = {
                            "userID"           : users[j].id,
                            "userName"         : users[j].name,
                            "postingId"        : posts[i].id,
                            "postingTitle"     : posts[i].title,
                            "postingContent"   : posts[i].content 
                        }
                        data.push(userPost);
                    }
                }
            }
            console.log(data);    
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            response.end(JSON.stringify({ "data" : data }));
        }
    }else if(method === "POST"){
        response.writeHead(200, {'Content-Type':'appliction/json'})
        //response.end(JSON.stringify({message: 'userCreated'}));
        // url이 /users/signup 이면 회원가입을 실행:
        if (url === "/users/signup") {
            let body = "";

            //콜백함수: 데이터를 모아서 하나의 스트링으로
            request.on("data", (data) => { 
                body += data;
            });

            //콜백함수: 
            request.on("end", ()=>{
                // 하나의 스트링으로 만든 body를 파싱해서 user에 할당
                const user = JSON.parse(body);

                // 전역변수 users에 입력받은 객체를 추가
                users.push({
                    id: user.id,
                    name: user.name,
                    email: user.email,
                    password: user.password,
                });

                // 데이터타입은 json으로 
                response.writeHead(200, {'Content-Type':'appliction/json'});

                // json으로 작성된 stringify(...)의 ...을 응답'body'에 표시
                response.end(JSON.stringify({
                    message : "userCreated",
                    "users" : users
                }));
            });
        // url이 /posts/signup 이면 게시글 입력을 실행:
        }else if(url === "/posts/signup"){
            let body = "";

            //콜백함수: 데이터를 모아서 하나의 스트링으로
            request.on("data", (data) => { 
                body += data;
            });

            //콜백함수: 
            request.on("end", ()=>{
                // 하나의 스트링으로 만든 body를 파싱해서 post에 할당
                const post = JSON.parse(body);

                 // 전역변수 posts에 입력받은 객체를 추가
                posts.push({
                    id: post.id,
                    title: post.title,
                    content: post.content,
                    userId: post.userId,
                });
                // 데이터타입은 json으로 
                response.writeHead(200, {'Content-Type':'appliction/json'});

                // json으로 작성된 stringify()의 객체 내용을 응답'body'에 표시
                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}`);
})

1-1. 추가한 소스코드

const httpRequestListener =  function(request, response){
    const { url, method } = request;
    if (method === 'GET'){
        // 생략
        else if (url === '/posts/inquire'){
            const data = [];
            for(let i = 0; i<posts.length; i++){
                for(let j = 0; j<users.length; j++){
                    if (users[j].id === posts[i].userId){
                        let userPost = {
                            "userID"           : users[j].id,
                            "userName"         : users[j].name,
                            "postingId"        : posts[i].id,
                            "postingTitle"     : posts[i].title,
                            "postingContent"   : posts[i].content 
                        }
                        data.push(userPost);
                    }
                }
            }
            console.log(data);    
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            response.end(JSON.stringify({ "data" : data }));
        }
    }
  //생략
}

2. 리스닝

 node apiServer1.js

3. 결과

3-1. ping-pong 확인하기

http -v GET http://127.0.0.1:8000/ping

3-2. 사용자 추가

http -v POST http://127.0.0.1:8000/users/signup id:=3 name="홍길동" email="hong@gmail.com" password="hong1234"

3-3. 게시물 추가

http -v POST http://127.0.0.1:8000/posts/signup id:=3 title="HTTP methods" content="GET, POST, DELETE" userId:=3

3-4. 게시물 조회하기

http -v GET http://127.0.0.1:8000/posts/inquire 

참고) 사용자, 게시물 추가하기 전에 조회했을 때:

참고2) POSTMAN으로 게시물 조회하기 기능 확인

profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글