FRONTEND

Vue- 영화 API 사용하기 (TMDB)

handcraft 2024. 4. 11. 11:33

 

 

Getting Started

Get started with the basics of the TMDB API.

developer.themoviedb.org

 

1. 회원가입하기 

2. profile > settings들어가기 

3.API > requestan API 

 

4.

https://developer.themoviedb.org/docs/getting-started  

에서 API Reference 에서 Getting Started

   Pick a language > javascript

   try it 코드 복사

const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer~~~~'
}
};

.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

 

options 는 기본 키 

fetch에서 url 은 

const data= await fetch(`https://api.themoviedb.org/3${url}`, options)
 

로 변경하기 list 나 detail등을 가져올수 있도록

예) 아래와 같은 fetch 가 이어지기 때문에 

fetch('https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc', options)

fetch('https://api.themoviedb.org/3/keyword/keyword_id', options)

 

* language=en-US == 언어 변경 가능

 

결과

vue 에서 

import {defineStore} from "pinia"
import {ref} from 'vue';

export const useMovieStore= defineStore ("movie",()=>{
const movie= ref(null);
const movieDetail = ref(null);
const isLoading = ref(false)

const fetchAPI = async (url) => {
isLoading.value = true;
const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer~~~',
}
};
const data= await fetch(`https://api.themoviedb.org/3${url}`, options)
.then(response => response.json())
.then(response => response)
.catch(err => console.error(err));
isLoading.value = false;
return data;
}
const getMoviesList = async(page = 1)=>{
const data = await fetchAPI(`/discover/movie?include_adult=false&include_video=false&language=ko&page=${page}&sort_by=popularity.desc`);
movie.value = data.results;
};

const getMovieDetail = async(id) => {
const data = await fetchAPI(`/movie/${id}?language=ko`)
movieDetail.value = data;

//원본
// const options = {
// method: 'GET',
// headers: {
// accept: 'application/json',
// Authorization: 'Bearerㅇ~~~~'
// }
// };
// return await fetch(`/movie/${id}?language=en-US`, options)

// .then((response) => response.json())
// .then((response) => (movieDetail.value = response))
// .catch((err) => console.error(err));
// idLoading.value=false;
};
 
return {
movie,
movieDetail,
isLoading,
getMoviesList,
getMovieDetail}
});

 

'FRONTEND' 카테고리의 다른 글

JSP _ 변수 선언 var, let 차이  (0) 2022.02.10
HTML 기초  (0) 2021.12.20