npm install axios --save
import axios from 'axios';
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';
//http request 拦截器
axios.interceptors.request.use(
config => {
// const token = getCookie('名称');
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
// if(token){
// config.params = {'token':token}
// }
return config;
},
error => {
return Promise.reject(err);
}
);
//http response 拦截器
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)
}
)
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/
export function get(url,params={}){
return new Promise((resolve,reject) => {
axios.get(url,{
params:params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
}
/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/
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)
})
},
其余的方法一样
欢迎光临 PHP开发笔记 (http://phpvi.com/) | Powered by Discuz! 6.1.0 |