전체 글 88

API Header

const getDadJoke = async () => { const config = { headers: { Accept: 'application/json' } } const res = await axios.get('https://icanhazdadjoke.com/', config) console.log(res); } 해당 icanhazdadjoke api는 json으로 받기 위해선 accecpt headers가 필요하기때문에 config 변수로 해당 값을 넣었다. https://icanhazdadjoke.com/api icanhazdadjoke icanhazdadjoke.com const getDadJoke = async () => { const config = { headers: { Accept: '..

AXIOS

axios.get("https://swapi.dev/api/people/1") .then(res => { console.log("RESPONSE : ", res) }) 입력시 출력으로 res의 데이터가 나온다. fetch("https://swapi.dev/api/people/1") // Promise 반환 .then(res => { console.log('RESOLVE!', res) }) axios를 사용하지 않았다면 코드 실행이 너무 빨라 res 데이터가 나오지 않았다. const getStarWarsPerson = async (id) => { try { const res = await axios.get(`https://swapi.dev/api/people/${id}/`); console.log(res..

Fetch API

fetch("https://swapi.dev/api/people/1") // Promise 반환 .then(res => { console.log('RESOLVE!', res) // resolve시 log가 뜨고 반환된 res가 나옴 }) .catch(e => { console.log("ERROR!", e) }) 하지만 res 값에선 우리가 원하는 정보가 api에서 오지 않았는데, 그 이유는 반환된 res가 바로 실행되어 들어가지 않음 res.json().then(data => console.log('JSON DONE', data)) 이걸 추가해주면 반환된 res를 json으로 읽어 data로 출력한다 fetch("https://swapi.dev/api/people/1") // Promise 반환 .the..

JSON parese, stringify, API 요청 종류, Http statue

JSON.parese(data) 를 하면 해당 data를 javaScript로 바꿔준다. JSON.stringify는 반대로 해당 data를 다른 언어 ( 파이썬 루비등 ) 로 볼 수 있게 바꿔준다. 대부분의 API는 JSON 포맷을 사용한다. Get : 정보를 가져올 때 Post : 정보를 어딘가로 보낼 때 ( 우리가 데이터를 보내서 데이터베이스에 저장 ) Delete : 삭제 Http statue는 코드로 보인다. 2로 시작 : 일반적으로 문제 x 404 : 존재하지 않는 endpoint로 요청했을때 ( endpoint란 https://swapi.dev/api/ 라는 기본 api가 있을때 뒤에 붙는 people/1 , planet/2 등등 ) 5로 시작 : 클라이언트보다 서버에 문제가 생겼을때 발생 ..

JS Try, catch 를 이용한 async 문제 해결

Try, catch try { // 문제를 잡아서 flkasdjflk.log(fldsk) } catch(e) { // 아래처럼 해결해준다 console.log("ITS OK!") } try, catch문은 try로 잡아준 코드가 error가 발생해서 다음 코드가 실행되지 않으면 catch에 쓰인 코드를 출력한다. const faekRequest = (url) => { return new Promise((resolve, reject) => { const delay = Math.floor(Math.random() * (4500)) + 500; setTimeout(() => { if (delay > 2000) { reject(`Connection Timeout`) } else { resolve(`Here is..

JS 비동기 async 함수, await

async 해당 async를 사용하면 함수를 비동기 함수로 언선해준다. 이는 곧 함수를 자동으로 promise로 반환해준다. async function hello() { } const sing = async () => { return 'LA LA LA LA' } // 출력값 Promise {: 'LA LA LA LA'} sing().then((data) => { console.log("PROMISE RESOLVED WITH:", data) }) // 출력값 PROMISE RESOLVED WITH: LA LA LA LA 이 함수는 async를 사용하지 않았다면 undefined가 출력되었겠지만, async를 사용해서 Promise {: undefined} 값이 나온다. ( 원래는 return new Pro..

JS Promise

promise의 상태는 3가지 이다. pending : 무언가를 기다리는 상태 resolved : 성공 reject : 실패 promise는 resolved나 reject일때 특정한 코드를 실행시켜줌 그러려면 함수 안에 콜백을 넣는게 아닌 promise 객체 자체에 콜백을 넣어야함 , 이후 함수가 promise 객체를 반환하는 걸 기다리면 됨. const fakeRequestPromise = (url) => { return new Promise((resolve, reject) => { const delay = Math.floor(Math.random() * (4500)) + 500; setTimeout(() => { if (delay > 4000) { reject('Connection Timeout :(..

JS 콜백(callback) 지옥

콜백 const fakeRequestCallback = (url, success, failure) => { const delay = Math.floor(Math.random() * 4500) + 500; setTimeout(() => { if (delay > 4000) { failure('Connection Timeout :(') } else { success(`Here is your fake data from ${url}`) } }, delay) } // delay가 4000 이상이면 failure해서 Connection Timeout, // 아니면 success해서 url을 불러온다. success가 첫번째 콜백, failure가 두번째 콜백 const fakeRequestCallback = (url..

기술 콜스택, WebApi와 단일스레드, 콜백

콜스택 JS는 기본적으로 콜스택으로 이루어져 있고 스택이란 기본적으로 후입선출이다. 이는 곧 책 a,b,c를 순서대로 쌓아 올렸을때, 책을 정리하기 위해선 맨 위의 c 책부터 빼는 것과 같이 가장 나중에 넣은 책을 가장 먼저 제거한다. 이는 곧 자바스크립트의 동작 원리이다. const multiply = (x, y) => x * y; const square = x => multiply(x, x); const isRightTriangle = (a, b, c) => ( square(a) + square(b) === sqare(c) ) 위 코드에서 콜스택은 이렇다. multiply(3,3) 9 // 해당값이 반환되어 (1) --------------------------------- square(3) mult..