본문 바로가기
TIL/The Complete Web Developer in 2021: Zero

HTTP/JSON/AJAX +Asynchronous Javascript(2021-02-18~2021-02-22)

by Dev_Dank 2021. 2. 18.

- 웹개발을 배우기 위해 Udemy에서 the-complete-web-developer-zero-to-mastery를 수강한 내용을 정리하는 포스팅입니다. 

- 틀린점이있거나 다른 의견이 있으시다면 언제든지 댓글로 남겨주시면 감사하겠습니다 :)


HTTP/HTTPS

HTML은 문서를 다른 컴퓨터로 부터 받아올수가없으면 소용이없다.  -> HTTP(Hyper Text Tranfer Protocol)를 팀버너스리가 또 개발.

클라이언트(브라우저)가 서버와 대화할떄 사용하는 언어로 생각 할 수 있다. 

-클라이언트로부터 서버로 보내는 메세지는 request
-서버로부터 온 메세지는  response 

HTTP의 종류는 4가지로 아래와 같이 존재. 

-GET: 무언가를 받아올떄 사용 (트위터 타임라인 불러오기)
-POST: 무언가를 서버에 올릴떄 사용 (트위터서버에 유저추가)
-PUT: 데이터 업데이트에 사용 (트윗수정)
-DELETE: 서버의 특정 데이터 삭제시 사용 (트윗삭제, 유저삭제)

서버가 반응해서 보내주는것들은 것은 2가지인데 하나는 HTTP 메세지이며(Status code 같은것들...) www.w3schools.com/tags/ref_httpmessages.asp

 

HTTP Messages

HTTP Status Messages HTML Error Messages When a browser requests a service from a web server, an error might occur, and the server might return an error code like "404 Not Found". It is common to name these errors HTML error messages. But these messages ar

www.w3schools.com

다른 하나는 HTML, CSS, JS, 이미지파일 등등이다. 

콘솔의 네트워크 탭에서 확인하는 모습1
콘솔의 네트워크 탭에서 확인하는 모습2 

지난강의에서 만든 form을 다시 가져와서 활용해보자. 

GET 메소드를 쓴경우 

모든 정보가 쿼리스트링에 나오게 된다. 

POST 메소드를 쓰게 되면 

쿼리스트링이 없어지고 form data를 활용해서 데이터를 주게된다. 

그런데 문제는 쿼리스트링이나 form data나 전부 비밀번호가 유출이 될 가능성이 있다는 것이다. 

한가지 해결책은 HTTPS(Hyper Text Transfer Protocol Secure)를 이용하는것이다. 

HTTPS 를 이용하면 통신이 암호화 되어서 암호키가 없으면 통신을 읽을수 가 없게 된다. 

JSON

JSON(Javascript Object Notation)은 브라우저와 서버가 데이터를 주고받을때사용하는 문법이다.  

JSON은 그저 text이기 떄문에 서버가 어떤언어(파이선, GO, 자바...)사용해도 읽을수 있다. 

자바스크립트에는 자체 JSON 함수가 있어서 활용이 가능하다. 

parse()는 받아온 JSON을 JS 오브젝트로 만들어주고 stringify는 반대로 JS 오브젝트를 JSON으로 만들어 준다. 

AJAX

www.w3schools.com/whatis/whatis_ajax.asp

옛날에는 브라우저에서 request 요청을 해서 자료를 서버로 부터 받아오면 전체 페이지를 전부 다시 로딩 해야됬음
(아마존에서 물건하나 클릭하면 페이지를 새로고침해서 모든 에셋을 전부 다시 로딩....)

듣는것만으로도 알수있듯이 이 방식은 매우 비효율 적임 

그래서 나온것이 AJAX

AJAX는 페이지가 처음 로딩된이후  필요한 부분만 불러온다. 

Robofriends 프로젝트에서 했었던 fetch가 예시다. 

또한 fetch에는 json()메소드가 있어서 받아오는 response를 json으로 만들어 줄 수 있다. 

Promises

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

 

Promise - JavaScript | MDN

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. To learn about the way promises work and how you can use them, we advise you to read Using promises first.A Promise is a proxy for a va

developer.mozilla.org

www.w3schools.com/js/js_promise.asp

 

JavaScript Promises

JavaScript Promises "I Promise a Result!" "Producing code" is code that can take some time "Consuming code" is code that must wait for the result A Promise is a JavaScript object that links producing code and consuming code JavaScript Promise Object A Java

www.w3schools.com

ES6에 추가된기능이며 매우 많은 곳에서 사용된다.

Promise는 미래에 하나의 값을 생성해낼수 있는 object이며 resolved value 이거나 특정이유가 있어서 resolved 되지 못할 수도 있다(rejected).

Promise는 3가지 상태 중 1가지로 있게 된다. 

-fulfullied(resolved)
-rejected
-pending

Promise가 도입되기 전에는 콜백을 이용해야했다(무언가가 실행되면 이 코드를 실행시켜라의 방식)

콜백을 사용하면 nesting이 계속 될수 있어서 복잡하다. 
Promise를 쓰면 위의코드를 이런 형식으로 간략화 시킬수 있다.

Promise를 만드는 문법은 이하와 같다. 

Promise의 사용법은 이하와 같다. 

then()은 새로운 promise를 반환한다. 

그리고 Promise 는 .catch를 사용해서 에러를 잡아 낼수 있다. 

.then에서 에러를 뿌려주니 catch에서 받아낸 모습

추가로 .catch가 어디에 오는지에 따라 잡아낼수있는 에러가 다르다. 

에러를 catch이후 발생시키니 'errror!'가 안뜨는 모습이다.

promise와 timeout을 이용한 설명은 강의(237) 13:12초를 참조

현실에서는 이하의 형태로 promise를 사용한다. 

promise.all()은 여러개의 promise를 받아서 1개의 array로 resolve하는 promise로 반환한다. 

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all 

 

Promise.all() - JavaScript | MDN

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the in

developer.mozilla.org

추가로 캡틴 판교님의 글이 정리가 잘되있어 참조로 추가한다.

joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/

 

자바스크립트 비동기 처리와 콜백 함수

(중급) 중급 자바스크립트 개발자가 되기 위한 자바스크립트 비동기 처리와 콜백 함수 이해하기. 콜백 지옥과 해결 방법 등

joshua1988.github.io

ES8 - Async Await

Async Await은 프로미스 기반으로 만들어진 ES8에서 새로 도입된 기능이다. 

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

 

async function - JavaScript | MDN

An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to expli

developer.mozilla.org

www.w3schools.com/js/js_async.asp

 

JavaScript Async

JavaScript Async "async and await make promises easier to write" async makes a function return a Promise await makes a function wait for a Promise Async Syntax The keyword async before a function makes the function return a promise: Example async function

www.w3schools.com

Async function은 사실상 promise를 반환하는 function이고 Syntactic sugar이다(기능은 똑같은데 더 보기 좋게 해주는것). 이것의 장점은 코드의 가독성이 크게 향상된다는 점이다. 

이렇게 쓰던 promise를 
이렇게 작성할 수가 있다. 
이렇게 작성했던 코드를
이렇게 작성할 수있다 (이번에는 function expression을 사용한 모습). (const [] 부분은 ES6 destructure를 이용) 그런데 위에서 작성했던 에러 판별용 catch는 어떻게 표현 해야할까??? -> JS의 try catch blocks를 사용하면 된다. 
에러부분 까지 구현한 모습

ES9 (ES2018)

주요한 기능 3가지가 추가 되었다. 

1. object spread operator

이하와 같이 ...을 사용해서 spread operator가 사용이 가능하다. 

spread 문법의 설명은 이하의 링크를 참조하자.

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

 

Spread syntax (...) - JavaScript | MDN

Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where ze

developer.mozilla.org

2.finally

promise 이후 작업을 추가한다(에러가 발생하던 정상적이던 마지막으로 항상 수행된다.)

finally는 인자를 아무것도 받지 않아서 ()으로만 써놓은것. 

3. for await of

for of로 iterable을 루프 할수 있었던것과 마찬가지로 await promise를 루프 할 수 있다. 

ES2020: allSettled()

Promise.all()에서는 인자가 하나라도 reject되면 에러를 발생시켰지만 allSettled()는 reject 되는게 있더라도 정상적으로 작동한다.

 

'TIL > The Complete Web Developer in 2021: Zero' 카테고리의 다른 글

APIs (2021-02-23)  (0) 2021.02.23
React.js (2021-02-15~17)  (0) 2021.02.15
NPM + NPM Scripts(2021-02-14)  (0) 2021.02.14
Git + Github + OpenSource Projects(2021-02-13)  (0) 2021.02.13
Command Line(2021-02-13)  (0) 2021.02.13

댓글