박준희 2021. 6. 4. 14:31

1. rest api와 라우팅

rest api

네트워크 구조의 한 형식

서버의 자원을 정의하고 자원에 대한 주소를 지정하는 방법

주소는 명사로 구성

주소 외에도 http요청 메서드를 사용

http 메서드

GET

서버 자원을 가져오고자 할 때 사용

요청의 본문에 데이터를 넣지 않음

데이터를 서버로 보내야 한다면 쿼리스트링을 사용

POST

요청의 본문에 새로 등록할 데이터를 넣음

PUT

서버에 자원을 요청에 들어 있는 자원으로 치환할 때 사용

PATCH

서버에 자원의 일부를 요청에 들어 있는 자원으로 치환할 때 사용

DELETE

서버의 자원을 삭제할 때 사용

 

주소 하나가 요청메서드를 여러개 가질 수 있음

 

서버확장

Scaling

 

주소설계

프로토콜 문서 작성

주소, 메서드, 어떤 역할, 어떻게 보내고 받나

 

restServer.js

const http = require("http");
const fs = require("fs");
const users = {};

const server = http.createServer((req,res) => {
    if(req.method == 'GET')
    {
        console.log(req.method + ", " + req.url);
        if( req.url == '/') {
            return fs.readFile('./restFront.html', (err, data) => {
                if(err) throw err;

                res.end(data);
            })
        } else if (req.url === "/users") {
            return res.end(JSON.stringify(users));
        }


        return fs.readFile(`.${req.url}`, (err, data) => {
            if(err) {
                res.writeHead(404, 'NOT FOUND');
                return res.end("NOT FOUND");
            }
            return res.end(data);
        })
    } else if (req.method === "POST") {
        if (req.url === "/users") {
            let body = "";
            req.on("data", data => {
                body += data;
            });
            return req.on('end', ()=>{
                const {name} = JSON.parse(body);
                const id = +new Date();
                users[id] = name;
                console.log(users);
                res.writeHead(201);
                res.end('등록성공');
            });
        }
    }

    
});

server.listen(8085, () => {
    console.log("8005번 포트에서 서버 대기중...");
});

 

restfront.js

function getUser() {
    console.log("getUser");
    let xhr = new XMLHttpRequest();
    xhr.onload = function() {
        if(xhr.status === 200) {
            let users = JSON.parse(xhr.responseText);

            let list = document.getElementById('list');
            list.innerHTML = '';
            Object.keys(users).map(function(key) {
                let userDiv = document.createElement('div');
                let span = document.createElement('span');
                span.textContent = users[key];
                userDiv.appendChild(span);
                list.appendChild(userDiv);
            });
        }
    };
    xhr.open("GET", "/users");
    xhr.send();
}

window.onload = getUser;

document.getElementById("form").addEventListener("submit", function(e) {
    e.preventDefault();
    
    let name = e.target.useranme.value;
    if(!name) {
        return alert("이름을 입력하세요");
    }

    console.log(name);

    let xhr = new XMLHttpRequest();
    xhr.onload = function () {
        if(xhr.status === 201) {
            getUser();
        } else {
            console.error();
        }
    };
    xhr.open("POST", "/users");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.send(JSON.stringify({name}));

    e.target.useranme.value = "";
});

 

restfront.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="./restfront.css" />
    <title>RESTful SERVER</title>
</head>
<body>
    <a >asdf</a>
    <form id="form">
        <input type="text" id="useranme"/>
        <button type="submit">등록</button>
    </form>
    <div id="list">

    </div>
</body>
<script src="./restfront.js"></script>
</html>

restfront.css

a {
    color: blue;
    text-decoration: none;
}