반응형
axios 사용방법 사이트
axios/axios: Promise based HTTP client for the browser and node.js (github.com)
GitHub - axios/axios: Promise based HTTP client for the browser and node.js
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js
github.com
functions -> movie.js 파일 생성
const axios = require('axios')
exports.handler = async function (event, context) {
console.log(event)
// 문자데이터를 객체데이터로 변환하여 변수에 저장
const payload = JSON.parse(event.body)
const { title, type, year, page, id } = payload;
const OMDB_API_KEY = '비밀';
const url = id
? `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&i=${id}`
: `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`;
// const url = `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}`;
try {
const {data} = await axios.get(url)
if (data.Error){
return {
statusCode: 400,
body: data.Error
}
}
return {
statusCode: 200,
body: JSON.stringify(data)
}
} catch (error) {
return {
statusCode: error.response.status,
body: error.message
}
}
}
store -> movie.js 파일 수정
// 비동기로 동작한다.
actions: {
async searchMovies({state, commit}, payload) {
// 영화검색을 동시에 동작하는 것을 방지
if(state.loading) {
return
}
commit('updateState', {
message: '',
loading: true
// 검색된 imdbID 데이터의 중복을 제거
// movies: _uniqBy(Search,'imdbID')
// message: 'Hello world',
// loading: true
})
try {
// const { title, type, number, year } = payload
// const OMDB_API_KEY = '7035c60c'
// http -> https 로 변경
//const res = await axios.get(`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=1`);
const res = await _fetchMovie({
// 전개연산자 사용
...payload,
page: 1
})
console.log(res);
const { Search, totalResults } = res.data
commit('updateState', {
// 검색된 imdbID 데이터의 중복을 제거
movies: _uniqBy(Search,'imdbID')
// message: 'Hello world',
// loading: true
})
console.log(totalResults) // 261
console.log(typeof totalResults) // string
const total = parseInt(totalResults, 10)
const pageLength = Math.ceil(total / 10)
// 추가 요청!
if (pageLength > 1) {
for (let page = 2; page <= pageLength; page += 1) {
if (page > payload.number / 10) {
// 반복문 종료
// 사용자가 지정한 갯수만큼 보여주도록 설정
break;
}
//const res = await axios.get(`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`);
const res = await _fetchMovie({
...payload,
page: page
})
const {Search} = res.data
commit('updateState', {
// _uniqBy 를 이용해서 중복 제거
movies: [
...state.movies,
..._uniqBy(Search, 'imdbID')
]
})
}
}
!!! 이부분수정 {message}
} catch ({message}) {
commit('updateState', {
// 초기화
movies: [],
// 메세지 출력
message: message
})
} finally {
commit('updateState', {
loading: false
})
}
},
async searchMovieWithId({state, commit}, payload) {
if(state.loading) return
commit('updateState', {
theMovie: {},
loading: true
})
const {id} = payload
try {
const res = await _fetchMovie(payload)
commit('updateState',{
theMovie: res.data
// id: id
})
console.log(res)
} catch(error) {
commit('updateState', {
theMovie: {}
})
} finally {
commit('updateState', {
loading: false
})
}
}
}
async function _fetchMovie(payload) {
// 서버리스 함수로 처리
return await axios.post('/.netlify/functions/movie', payload)
// const { title, type, year, page, id } = payload;
// const OMDB_API_KEY = '비밀';
// const url = id
// ? `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&i=${id}`
// : `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`;
// // const url = `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}`;
// return new Promise((resolve, reject) => {
// axios.get(url)
// .then((res) => {
// // console.log(res)
// if (res.data.Error) {
// reject(res.data.Error)
// }
// resolve(res)
// })
// .catch((err) => {
// reject(err.message)
// })
// })
}
개발서버 실행: npm run dev:netlify
post방식으로 파라미터를 안보여주는 것을 확인
반응형
'프론트엔드 > Vue.js' 카테고리의 다른 글
포트 수정 및 배포 (0) | 2022.01.15 |
---|---|
로컬 및 서버의 환경 변수 구성 (0) | 2022.01.15 |
Netlify-CLI 구성 (0) | 2022.01.15 |
Netlify Serverless Function (0) | 2022.01.14 |
SPA (0) | 2022.01.14 |