Axios 是一個 JavaScript 函式庫,主要用來簡化在瀏覽器和Node.js中處理HTTP請求的流程。這個函式庫讓你可以輕鬆地跟網頁伺服器或其他網路服務互動,不論是要向伺服器取得資料或是將資料傳送到伺服器都變得相當容易。Axios 的一些特點包括:
-
使用簡單:Axios 提供了簡潔的應用程式介面,你可以用它來建立HTTP請求、設定請求的標頭、參數等。
-
Promise 支援:Axios 使用Promise來處理請求和回應,這讓處理非同步操作變得簡單且易於閱讀。
-
自動資料格式轉換:它可以自動處理JSON資料的解析,並支援其他資料格式的自動轉換。
-
請求和回應攔截器:你可以設定攔截器來攔截請求和回應,以新增全域性的處理邏輯,像是驗證、記錄等功能。
-
跨瀏覽器相容性:Axios在多種瀏覽器和環境中都有良好的相容性,也支援跨域請求。
以下就以 Vue.js 來說明如何使用 axios 串接資料:
Options API
get
axios.get(url)
.then( (response) =>{
console.log(response);
})
.catch( (error)=> {
console.log(error);
});
or
axios({
method: 'get',
url: url
}).then( (response) =>{
console.log(response);
})
.catch( (error)=> {
console.log(error);
});
帶參數:
axios.get('/user?ID=12345')
.then( (response) =>{
console.log(response); })
.catch( (error) =>{
console.log(error);
});
or
axios.get('/user',
{ params: {
ID: 12345
}
}).then( (response)=> {
console.log(response);
}).catch( (error)=> {
console.log(error);
});
or
axios({
method: 'get',
url: '/user/,
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
post 原則上跟 get 寫法也差不多
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
接著來看一下 Compotision API 的寫法,基本的概念差不多,但就注意 Compotision API 的用法就好
程式碼的部分:
const { createApp, reactive, onMounted } = Vue;
createApp({
setup(){
const schools=reactive({
data: null
})
onMounted(()=>{
axios.get('taoyuan.json')
.then(response => {
// console.log(response)
schools.data=response.data
})
})
return {
schools
}
}
}).mount('#app')
帶參數或 post 的方法再參考 Options API 的寫法即可。