[JavaScript] fetch、ajax、axios 基本用法(前後端溝通、串接API)
記錄一下.. 面試或工作、前後端溝通上 (一般 HTML 或 React、Node.js) 都常用到..
我個人是比較喜歡用 axios ~
股票 API (JSON 格式):
https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=20210702&stockNo=2330
會看到這樣的資料 (json)
如果以上不能用,可以使用這位大哥的 API (text 格式):https://script.google.com/macros/s/AKfycbw5PnzwybI_VoZaHz65TpA5DYuLkxIF-HUGjJ6jRTOje0E6bVo/exec?name=${name}&age=${age}
會看到這樣的資料 (text)
程式撈取結果大概會長這樣
fetch:
1. promise based (可改為 async/await)
2. HTML5 API
let btn = document.querySelector('.btn');
btn.addEventListener('click', () => {
fetch('https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=20210702&stockNo=2330', {
method: 'GET',
})
.then((response) => {
return response.json();
})
.then((result) => {
console.log(result);
});
});
ajax:
1. xhr based
2. 須引用
jQuery
$('.btn').on('click', () => {
$.ajax({
method: 'GET',
url: 'https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=20210702',
data: { stockNo: 2330 },
dataType: 'json',
})
.done((data) => {
console.log(data);
})
.fail((error) => {
console.error('error:', error);
})
.always(() => {
console.log('完成');
});
});
axios:
1. promise based (可改為 async/await)
2. 須透過 npm or yarn 安裝 or
引用 cdn,請參考官方
onClick={() => {
axios.get(`https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=20210702`, {
params: {
stockNo: 2330,
},
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.error('error', error)
})
}}



留言
張貼留言