【JS】學習筆記-用axios發送請求
axios的用法與XMLHttpReques相同,一樣是一個由客戶端向遠端請求(GET、POST)的方法,它是基於Promise開發的,也可支援Promise API
▌axios基本了解
整理自官方文件
可以送出XMLHttpRequests到伺服器
Make http requests from node.js
支援Promise API
可以取消請求
自動將格式轉換為JSON
幫保護客戶端被XSRF攻擊
▌安裝
由於是第三方開發,所以要進行安裝
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' ,{參數,也可以不要傳參數}) .then(function (response ) { console .log(response); }) .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 function getUserAccount ( ) { return axios.get('/user/12345' ); } function getUserPermissions ( ) { return axios.get('/user/12345/permissions' ); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms ) { }));
GET
1 2 3 4 5 6 7 8 9 10 11 12 13 14 axios({ method: 'get' , url: 'https://api.user' , baseURL: '' , params: {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' )
參考資料: