axios的使用方法–即GET、POST、 OPTION 、請求攔截的使用
- axios怎樣在全局使用
- get傳遞參數和傳遞token
- post傳遞參數和token
- option的使用
- *攔截器的使用
axios怎樣在全局使用
0 . 安裝axios npm/cnpm install axios --save
1 .在main.js將axios放在原型上
> 1.0 import axios from 'axios'
> 1.1 Vue.prototype.axios = axios
2. 在你想用的vue文件中直接使用this.axios({method:'',url:''}).then().catch()直接使用
axios中GET請求的使用
axios. get(){
this.axios({
method:"GET",
url:'https://api.github.com',
params:{
user:999,//get請求中使用params傳遞參數
},
header:{
token:123,//使用token在header裏面
},
}).then((response)=>{
console.log(response.data)
}).catch((err)=>{})
},
axios中POST請求的使用
- 注意傳參方式
axios. post(){
this.axios({
method:'POST',
url:'https://api.github.com',
data:{
userId:12,
},
header:{
token:123,
},
}).then((res)=>{
console.log(res)
}).catch((err)=>{})
},
axios中option請求的使用
- 注意傳參方式
axios.defaults.baseURL = 'https://api.example.com'; //不用重複去寫url
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; //不用重複去傳token
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios中攔截器的使用
- 注意傳參方式
this.axios.interceptors.request.use((config)=>{
console.log('請求前的攔截');
console.log('loading.....');
return config
}),
this.axios.interceptors.response.use((response)=>{
console.log('響應攔截');//響應攔截
return response;
})