因為是JS初學者向,本篇文章以Axois為例!入門白話級教學。
- 記得申請API憑證
2. 啟用你的API服務
在搜尋欄位搜尋YouTube Data API,然後啟用它!
3. 再來就可以開始寫程式了
首先要記得引入插件和你的JS文件
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script src="你的文件.js" ></script>
引入完成之後,使用最簡單到不行的程式,總之先取得資料
axios.get('https://www.googleapis.com/youtube/v3/search',
{
params: {
part: 'snippet',
q: 'Aimer+歌詞',
maxResults: 10,
key: '你申請的API憑證'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
用箭頭函式就可以省略成這樣
.then(res => {
console.log(res.data.items);
}).catch(e => console.log(e))
這裡使用的是VScode撰寫
因為我們沒有刻網頁,也沒有任何輸出
所以打開LiveServer來瀏覽
右鍵「檢查」或打開「開發人員工具」的Console就會出現以下結果
最一開始根本不知道會拿到什麼資料
所以要配合YouTube API的官方文件來服用
像是要找出你要的資料是什麼
知道整包資料的裡面有什麼
並且你需要取得的資料是什麼(例如:封面是thumbnails)
再來可以做的事情就有許多
例如:發現「標題」是snippet裡面的title,那就來拿拿看標題
let data = [];
let keyword;axios.get('https://www.googleapis.com/youtube/v3/search',
{
params: {
part: 'snippet',
q: 'Aimer',
maxResults: 10,
regionCode: 'JP',
key: '你申請的API憑證'
}
}).then(res => {/* console.log(res.data.items);*/data = res.data.items;
renderData();}).catch(e => console.log(e))function renderData() {
data.forEach(function(item,index){
console.log(item.snippet.title);
})
}
就只是多了一個遍歷的forEach來提取資料
最後將snippet.title的影片標題印出
結果如下
到現在資料都還沒過濾,再來還能再想想要怎麼玩了~