주간 회고(WIL) 1주차

Hwanhoon KIM·2023년 5월 21일
0

5일 동안 한 미니프로젝트에서 많은 것을 배웠다.
HTML, CSS 기본실력을 다질 수 있게끔 간단한 웹사이트를 만들어봤고, 가장 중요한것은 HTTP request였다. flask와 몽고DB를 이용한 GET, POST은 어느정도 이해가 갔지만 아직 PUT과 DELETE는 완벽히 공부하진 못했다. 이거 쓴 다음에 해야지..

이번에 가장 중요하게 공부한 부분이다.

// script.js
function getData() {
        fetch('/message-data-request', { method: 'GET' })
            .then((res) => {
                if (!res.ok) {
                    throw new Error('에러발생')
                }
                res.json()})
            .then((data) => {console.log(data)})
            )
            .catch((err) => console.log(err));
    }
  1. 클라이언트에서 fetch'/message-data-request'이라는 url에 GET 요청을 한다.
fetch('/message-data-request', { method: 'GET' })
  1. 서버에서 요청을 받아서 데이터를 찾고 골라서 전송해준다.
# app.py
@app.route("/message-data-request", methods={"GET"})
def getting_data():
    data = db.sample.find({}, {"_id": False})
    data_to_send = list(data)

    return jsonify({"result": data_to_send})
  1. jsonify 된 즉, .json 파일을 다시 클라이언트에서 받아서 작업을 이어간다.
	.then((res) => {
                if (!res.ok) {
                    throw new Error('에러발생')
                }
                res.json()})
            .then((data) => {console.log(data)})
            )
            .catch((err) => console.log(err));

=> 서버에서 받은 json파일을 res로 놓고, res가 괜찮지 않으면(ok) 에러를 내고, 괜찮으면 res.json()함수로 json화 시킨다.
그리고 그것을 다시 data로 놓고, 필요한 작업을 한다. (주로 object니까 반복문으로 돌린다.)
에러가 있으면 catch해서 콘솔에 로그한다.

이것은 async 함수와 await으로도 다음과 같이 만들수가 있다.

async function 가져오기() {
    const res = await fetch('url');
    if (!res.ok) {
      throw new Error('에러발생');
    }
    const result = await res.json();
    console.log(result);
  }
  가져오기().catch(() => {
    console.log('에러발생');
  });

또한 라이브러리를 사용하여 할 수도 있는데, 제이쿼리를 사용한다면,

$.ajax({
    url: '/edit-message-content',
    type: 'PUT',
    data: request,
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
    },
    error: function(err) {
      console.log(err);
    }

이렇게 할 수도 있고, axios 라이브러리로도 많이 하는 것 같아보인다.

axios
    .get('url')
    .then((res) => {
      console.log(res.data);
    })
    .catch((err) => console.log(err));

PUT과 DELETE도 빨리 공부해서 적응 완료 해야겠다.
다음주도 파이팅 하자!

profile
Fullstack Developer, I post about HTML, CSS(SASS, LESS), JavaScript, React, Next, TypeScript.

0개의 댓글