0%

【JS】學習筆記-用axios發送請求

【JS】學習筆記-用axios發送請求

axios的用法與XMLHttpReques相同,一樣是一個由客戶端向遠端請求(GET、POST)的方法,它是基於Promise開發的,也可支援Promise API

▌axios基本了解

整理自官方文件

  • 可以送出XMLHttpRequests到伺服器
  • Make http requests from node.js
  • 支援Promise API
  • 可以取消請求
  • 自動將格式轉換為JSON
  • 幫保護客戶端被XSRF攻擊

▌安裝

由於是第三方開發,所以要進行安裝

  • npm
1
$ npm install axios
  • CDN
1
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

## ▌基本使用-GET、POST 用法跟Promise非常相似 ### GET
1
2
3
4
5
6
7
8
9
10

axios.get('url',{參數,也可以不要傳參數})
//與Promise非常相像,成功用then接收
.then(function(response){
console.log(response);
})
//失敗用catch
.catch(function(error){
console.log(error);
});

我們來撈出口到照地圖的資料試試看回傳了什麼

可以看到它回傳了一個物件,可以從這些物件找到想要的使用的資料

POST

1
2
3
4
5
6
7
8
9
10
11

axios.post('url', {
account: 123@mail.com,
password: '123123'
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});

▌發出多個請求-axios.all([])、axios.spread()接收資料

這個也與Promise非常相似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//用函式retrun一個axios
function getUserAccount() {
return axios.get('/user/12345');
}

function getUserPermissions() {
return axios.get('/user/12345/permissions');
}

//axios.all(用陣列列出要執行的請求)
axios.all([getUserAccount(), getUserPermissions()])
//成功用then接收,並用axios.spread()接收各請求的數據
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14

axios({
method: 'get', //預設式get,沒有大小之分
url: 'https://api.user',//請求網址,必填
baseURL: '',//直接加在url前面的絕對位置,在同個網域底下可以使用
params: {ID:123}, //url後要接的參數 url/ID=123
timeout: 1000 //逾時設定,超過這個時間就會被終止
})
.then(function(res){
console.log(res)
})
.catch(function(rej){
console.log(rej)
})

POST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

axios({
method: 'post',
url: 'https://api.user',
data:{//傳送資料
account: '123@gmail.com',
password: 123123
}
})
.then(function(res){
console.log(res)
})
.catch(function(rej){
console.log(rej)
})

▌建立一個實例instance-axios.create({})

我們可以建議一個新的instance,有自己的名字與config
就可以分門別類,整理自己要請求的API

1
2
3
4
5
6
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
instance.get('url')

參考資料: