2022-01-14 TIL.02

MINBOK·2022년 1월 14일
0

Study

목록 보기
5/12

참고 - 아래는 이 링크의 일부분을 정리한 것입니다.
https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/

최종 완성본은 여기로
https://minbok-1998.github.io/GhibliAPI/

목표

우리는 Studio Ghibli API를 연결하여 JavaScript로 데이터를
검색하여 웹 사이트에 보여주는 간단한 웹앱을 만들 것입니다.

무엇을 배울 수 있을까? :

  • Web API가 무엇인가
  • HTTP request GET을 JavaScript에 어떻게 사용하는가
  • 어떻게 JavaScript로 HTML요소를 생성하고 보여주는가

API란?

API(Application Program Interface)는 소프트웨어가 다른 소프트웨어와 통신할 수 있게하는 소프트웨어 구성 요소 간의 통신 방법 집합입니다.

  • Create - POST - 새로운 resource 생성
  • Read - GET - resource 검색
  • Update - PUT/PATCH - 존재하는 resource 업데이트
  • Delete - DELETE - resource 삭제

HTTP request을 통한 데이터 검색

var request = new XMLHttpRequest()
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function () {
  // Begin accessing JSON data here
}
request.send()

XMLHttpRequest란?

서버에 데이터를 요청하기 위한 내장 객체,
서버로부터 XML 데이터를 전송받아 처리한다.

웹 페이지 전체를 다시 로딩하지 않고 일부분만을 갱신할 수 있음

✨ 참고 - XMLHttpRequest
http://www.tcpschool.com/xml/xml_dom_xmlHttpRequest

.open()

문서 작성을 위해 문서를 열어주는 메서드

document.open();
document.write("<p>Hello world!</p>");
document.write("<p>I am a fish</p>");
document.write("<p>The number is 42</p>");
document.close();

.open() 메서드의 세 번째 인수로 true를 전달하면 서버에 비동기식 요청을 보낼 수 있다.

✨ 참고 - .open()
https://developer.mozilla.org/en-US/docs/Web/API/Document/open

JSON 응답 작업

앞서 받은 HTTP request는 JSON 형태로 되어있는데,
이를 JavaScript 객체로 변환하는 작업이 필요하다.

JSON.parse()를 사용해 응답을 분석하고, JavaScript 배열 객체에 모든 JSON을 포함하는 데이터 변수를 생성할 것이다.

forEach()를 사용하여 각 영화의 제목을 콘솔에 찍어봄으로
올바르게 작동하는지 확인해볼 것이다.

JSON.parse() 메서드

JSON 문자열의 구문을 분석하고,
그 결과로 JavaScript 값이나 객체를 생성함

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);  // 42

console.log(obj.result);  // true

✨ 참고 - JSON.parse()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

forEach() 메서드

주어진 함수를 배열 요소 각각에 대해 실행

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// "a"
// "b"
// "c"

✨ 참고 - forEach()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

데이터 화면에 출력하기

프론트엔드 화면에 정보를 출력하기 위해서, JS가 HTML과 통신할 수 있도록 하는 DOM을 사용할 것입니다.

getElementById()로 index.html 파일의 <div id="root">에 접근할 수 있습니다.
createElement()로 요소를 생성할 수 있습니다.

DOM으로 생성한 요소들을 <div id="root">안에 배치하기 위해
appendChild()를 사용하겠습니다.

appendChild()

부모 노드에 마지막 자식요소로 자식노드를 추가함

<ul id="myList">
  <li>Coffee</li>
  <li>Tea</li>
</ul>
// Create a <li> node
var node = document.createElement("LI");
// Create a text node
var textnode = document.createTextNode("Water");
// Append the text to <li>
node.appendChild(textnode);
// Append <li> to <ul> with id="myList"
document.getElementById("myList").appendChild(node);

// Coffee
// Tea
// Water

✨ 참고 - Node.appendChild()
https://developer.mozilla.org/ko/docs/Web/API/Node/appendChild

https://www.w3schools.com/jsref/met_node_appendchild.asp

지금, 우리가 DOM으로 만든 요소들은 개발자 도구의 Elements 탭에서만 보입니다.

textContent를 사용하여 HTML 요소의 텍스트를 API의 데이터로 설정합니다.

설명을 제한하고, 각각의 카드 길이를 동일하게 하기위해서
p태그에 substring()를 사용합니다.

textContent

노드와 그 자손의 텍스트 콘텐츠를 가져옵니다.

<innerHTML과의 차이점>
Element.innerHTML는 이름 그대로 HTML을 반환합니다.
간혹 innerHTML을 사용해 요소의 텍스트를 가져오거나 쓰는 경우가 있지만, HTML로 분석할 필요가 없다는 점에서 textContent의 성능이 더 좋습니다.

이에 더해, textContent는 XSS 공격의 위험이 없습니다.

✨ 참고 - Node.textContent
https://developer.mozilla.org/ko/docs/Web/API/Node/textContent
https://www.w3schools.com/jsref/prop_node_textcontent.asp (예제 참고)

substring()

string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지
문자열의 부분 문자열을 반환

  • 만약 indexEnd 가 생략된 경우, substring() 문자열의
    끝까지 모든 문자를 추출합니다.
  • 만약 indexStart 가 indexEnd와 같을 경우, 빈 문자열을 반환합니다.
  • 만약 indexStart 가 indexEnd보다 큰 경우, substring() 메서드는
    마치 두 개의 인자를 바꾼 듯 작동하게 됩니다.
const str = 'Mozilla';

console.log(str.substring(1, 3));
// "oz"

console.log(str.substring(2));
// "zilla"

✨ 참고 - String.prototype.substring()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

0개의 댓글