第一步还是先下载axios第二步/src/utils/目录下建立一个htttp.js
import axios from 'axios';
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';
axios.interceptors.request.use(
config => {
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
return config;
},
error => {
return Promise.reject(err);
}
);
axios.interceptors.response.use(
response => {
if(response.data.errCode ==2){
router.push({
path:"/login",
querry:{redirect:router.currentRoute.fullPath}
})
}
return response;
},
error => {
return Promise.reject(error)
}
)
export function get(url,params={}){
return new Promise((resolve,reject) => {
axios.get(url,{
params:params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
}
export function post(url,data = {}){
return new Promise((resolve,reject) => {
axios.post(url,data)
.then(response => {
resolve(response.data);
},err => {
reject(err)
})
})
}
第三步
在main.js中引入
import {post,get} from './utils/http'
Vue.prototype.$post=post;
Vue.prototype.$get=get;
最后在组件里直接使用
mounted(){
this.$post('/api/v2/movie/top250')
.then((response) => {
console.log(response)
})
},
其余的方法一样