[VANILA JS NINJA] MEAL FINDER (1) api 작성 (21/05/13)

NinjaJuunzzi·2021년 5월 12일
0

[VANILA JS NINJA]

목록 보기
5/9

에러

VM228:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
  fetch(`www.themealdb.com/api/json/v1/1/random.php`, {
    headers: { Accept: "application/json" },
  })
    .then((res) => res.json())
    .then((result) => console.log(result));

다음과 같이 비동기 요청하면 저 에러남..

아예 오는 데이터가 없음. 응답이 오지 못하는 경우이다. 왜 비동기 요청에 실패하는 지 파악해보자

에러 해결

  fetch(`https://www.themealdb.com/api/json/v1/1/random.php`, {
    headers: { Accept: "application/json" },
  })
    .then((res) => res.json())
    .then((result) => console.log(result));
  • https를 앞에 붙여주니 제대로 동작함.

javascript define params

다음과 같이하면된다.

/**
 * Queries a Baz for items.
 * @param {number} groupNum Subgroup id to query.
 * @param {string|number|null} term An itemName,
 *     or itemId, or null to search everything.
 */

Api.js

const fetcher = async (KEY, keyword = null) => {
  const url = `https://${API_KEY}${KEY}${keyword}`;


  const res = await fetch(url);
  if (!res.ok) {
    throw new Error("삐용삐용 에러발생");
  }
  return await res.json();
};

console.log(fetcher(SEARCH_KEY, "steak")); // Promise 출력

(async () => {
  console.log(await fetcher(SEARCH_KEY, "steak"));
})(); // 원하는 객체값 출력
  • API_KEY : 모든 API가 공통으로 갖는 키

  • KEY : API를 구분하는 키

  • keyword : API 요청에 넣어줄 인자

profile
Frontend Ninja

0개의 댓글