axios的基本特征
axios是一個基於Peomise用於瀏覽器和node.js的HTTP客戶端
它具有以下特征:
- 支持瀏覽器和node.js
- 支持promise
- 能攔截請求和響應
- 自動轉換JSON數據
axios的基本用法
axios.get('/adata') .then(ret => { //data屬性是固定的,用於獲取后台的響應數據 sonsole.log(ret.data); })
axios的常用API
- get:查詢數據
- post:添加數據
- put:修改數據
- delete:刪除數據
axios的參數傳遞
GET傳遞參數
- 通過URL傳遞參數
//傳統URL傳遞參數
axios.get('/adata?id') .then(ret => { console.log(ret.data); })
//Restful形式傳遞參數
axios.get('/adata/123')
.then(ret => {
console.log(ret.data);
})
后台獲取書
//傳統URL傳遞參數、
app.get('/adata',(req,res) => {
res.send('axios get 傳遞參數' + req.query.id);
})
//Restful形式傳遞參數、
app.get('/adata',(req,res) => {
res.send('axios get 傳遞參數' + req.params.id);
})
- 通過params選項傳遞參數
axios.get('/adata',{ params:{ id:123 } }) .then(ret => { console.log(ret.data); })
DELETE傳遞參數
- 參數傳遞與GET相似
POST傳遞參數
- 通過選項傳遞參數(默認傳遞的 json 格式的數據)
axios.post('/adata',{ uname:'tom',
pwd: 123 }).then(ret => { console.log(ret.data); })
- 通過URLSearchParams傳遞參數(application/x-www-form-ur;encoded)
const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/api/test',params).then(ret=>{ console.log(ret.data); })
PUT傳遞參數
- 參數傳參與POST相似
axios的響應結果
響應結果的主要屬性
- data:實際響應回來的數據
- headers:響應頭信息
- status:響應狀態碼
- statusText:響應狀態信息
通過調用后台,在頁面中運行,通過控制台查看返回的對象
axios.post('/axios-json').then(ret => {
console.log(ret);
})
axios的全局配置
- axios.defaults.timeout = 3000; //超時時間
- axios.defaults.baseURL = 'http://localhost:3000/'; //默認地址axios.defaults.headers['mytoken'] = 'hello'; //設置請求頭