연습장

[연습장] Vue3 : API를 통한 영화 목록을 만들어보자. (2) API를 통해 데이터를 가져오자. ( feat. 네이버 오픈 API )

모찌바라기 2022. 2. 20. 01:17
728x90
반응형

저번에 화면은 만들어 보았다. 그럼 실제로 데이터를 가져와야 하는데, 보통 Vue프로젝트에서는 FireDB를 많이

쓴다고 한다. 잘은 모르겠지만... 나는 그냥 API를 통해 데이터를 가져와서 화면에 뿌려줘 보겠다.

본 글에서는 문화 공공데이터광장 이라는 곳을 이용하겠다.

 

API 인증키 신청

============================================================================

아래 링크로 접속해주자.

https://developers.naver.com/docs/common/openapiguide/

 

API 공통 가이드 - Open API 가이드

API 공통 가이드 네이버 오픈API는 네이버 플랫폼의 기능을 외부 개발자가 쉽게 이용할 수 있게 웹 또는 SDK 형태로 공개한 기술들입니다. 네이버 오픈API로 활용할 수 있는 기술에는 네이버 로그인

developers.naver.com

 

그리고 네이버 오픈API 신청 및 사용법은 아래를 천천히 읽어보자. ( 조금 더러움... )

 

https://bongra.tistory.com/130

 

[기타] 네이버 오픈 API 서비스 URL ( feat. Live server ) * 수정

2022-02-28 수정 ============================================================================ 진짜 개발은 머리가 좋아야 하는 것 같다. 기존에 URL을 통한 프록시 서버를 통해 API를 호출하는 건 됬는데, 왜..

bongra.tistory.com

 

 

API 요청

============================================================================

자. 이제 인증키를 가지고 API를 요청할건데.. 비동기 통신을 통해 request를 하려고 한다.

보통 ajax를 사용하는데, 그냥 ajax는 너무 복잡하고, vue에서 jquery를 이용해서 ajax를 사용하는 건 쪼끔 그렇고..

외부 라이브러리 axios를 사용하려 한다. 외부 라이브러리이기 때문에 당연히 설치를...

터미널에 아래 명령어를 입력해준다.

npm install --save axios vue-axios

그럼 axios가 설치 된 것을 package.json에서 확인할 수 있다.

vue-axios는 반드시 설치할 필요는 없다!

 

이제 main.js에 다음 코드를 추가해준다.

 

// eslint-disable-next-line no-unused-vars
import axios from 'axios' --axios를 import 해옴
import VueAxios from 'vue-axios' -- vue-axios를 import 해옴

const app = createApp(App) -- app 객체 생성
app.use(VueAxios, axios) -- app에 axios를 사용하겠다고 선언 ( 작성 안해줘도 됨 )

app.config.globalProperties.axios = axios; -- axios를 전역화 ( 다른 컴포넌트에서 사용 가능하도록 )

 

이제 해당 프로젝트에서 axios를 사용할 수 있게 되었으니, 실제로 API요청을 하는 코드를 작성해보자.

나는 MovieList에 데이터를 뿌려줄 거기 때문에, MovieList가 mounted될 때

getMovieList라는 함수를 호출 하도록 할 것이다. getMovieList는 axios를 통해 영화목록을 가져오는 함수이다.

아래 코드를 MovieList.vue에 추가해준다.

 

mounted () { 
      this.getMovieList(); // MovieList가 화면에 랜더링 되었을 때 getMovieList 함수를 호출한다.
    },
      methods : {
      getMovieList : function(){ // API요청을 통해 영화목록을 받아온다.구보씨 일보
          let self = this;
          const URL = "/v1/search/movie.json?query=%EC%A3%BC%EC%8B%9D&display=10&start=1&genre=1"; /*URL*/
          const clientId = 'n9KqdakFPww8Um1PXnUK';
          const clientSecret = '8E------S3';

          this.$axios.get(URL,
              {headers : { 
                          'Accept' : 'application/json',
                          'X-Naver-Client-Id': clientId,
                          'X-Naver-Client-Secret': clientSecret}
              }).then((response) => { // 실제 API를 요청한다/
            console.log(response.data);
            let test = [];
            test = test.concat(response.data.items); // 받아온 데이터를 movieList 배열에 넣어준다.
            this.movieList = this.movieList.concat(test);
          })
      }
   }

 

이렇게 추가 해주면 API를 통해 제대로 데이터를 가져오는 것을 볼 수 있다.

 

데이터를 가져온 모습

이렇게 성공적으로 axios를 통해 데이터를 가져왔다. 다음 글에서는 이 데이터를 가지고

직접 리스트에 뿌려보는 것을 해보자. main.js와 MovieList.vue의 전체코드는 아래를 참조하자.

 

main.js

import { createApp } from 'vue'
import App from './App.vue'
// eslint-disable-next-line no-unused-vars
import axios from 'axios'

const app = createApp(App)
app.config.globalProperties.$axios = axios; //axios를 다른 전역화
app.mount('#app')

import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap"

 

MoiveList.vue

<template>
<div>
  <section class="py-5 text-center container"> 
    <div class="row py-lg-5">
      <div class="col-lg-6 col-md-8 mx-auto">
        <h1 class="fw-light">Album example</h1>
        <p class="lead text-muted">Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely.</p>
        <p>
          <a href="#" class="btn btn-primary my-2">Main call to action</a>
          <a href="#" class="btn btn-secondary my-2">Secondary action</a>
        </p>
      </div>
    </div>
  </section>

  <div class="album py-5 bg-light">
    <div class="container">

      <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
        <div class="col" v-for="data in movieList" :key="data">
          <div class="card shadow-sm">
            <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg>

            <div class="card-body">
              <p class="card-text">{{data.title}}</p>
              <p class="card-text" v-text="getDes(data.description)"></p>
              <div class="d-flex justify-content-between align-items-center">
                <div class="btn-group">
                  <button type="button" class="btn btn-sm btn-outline-secondary">상세보기</button>
                </div>
                <small class="text-muted">{{data.regDate}}</small>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</template>

<script>
export default ({
    data () {
      return {
        movieList : []
      }
    },
    mounted () { 
      this.getMovieList(); // MovieList가 화면에 랜더링 되었을 때 getMovieList 함수를 호출한다.
    },
    methods : {
      getMovieList : function(){ // API요청을 통해 영화목록을 받아온다.구보씨 일보
          let self = this;
          const URL = "/v1/search/movie.json?query=%EC%A3%BC%EC%8B%9D&display=10&start=1&genre=1"; /*URL*/
          const clientId = 'n9KqdakFPww8Um1PXnUK';
          const clientSecret = '8EqBZkrvS3';

          this.$axios.get(URL,
              {headers : { 
                          'Accept' : 'application/json',
                          'X-Naver-Client-Id': clientId,
                          'X-Naver-Client-Secret': clientSecret}
              }).then((response) => { // 실제 API를 요청한다/
            console.log(response.data);
            let test = [];
            test = test.concat(response.data.items); // 받아온 데이터를 movieList 배열에 넣어준다.
            this.movieList = this.movieList.concat(test);
          })
      }
    }
})
</script>
728x90
반응형