axios封装

初始化文件路径- -》定义http.js文件--》main.js引入http.js文件,全局定义事件--》使用

import axios from 'axios';
import { Message } from 'element-ui';

axios. defaults. timeout = 5000;
axios. defaults. baseURL = '';


//http request 拦截器
axios. interceptors. request. use(
config => {
// const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
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 fetch( 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)
})
})
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch( url, data = {}) {
return new Promise(( resolve, reject) => {
axios. patch( url, data)
. then( response => {
resolve( response. data);
}, err => {
reject( err)
})
})
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put( url, data = {}) {
return new Promise(( resolve, reject) => {
axios. put( url, data)
. then( response => {
resolve( response. data);
}, err => {
reject( err)
})
})
}


import axios from 'axios'
import { post, fetch, patch, put} from '../utils/http'
//定义全局变量
Vue. prototype. $post= post;
Vue. prototype. $fetch= fetch;
Vue. prototype. $patch= patch;
Vue. prototype. $put= put;


这个是我的helloworld文件 (我用来测axios是否封装成功)

< template >
< div class= "hello" >
< h1 >{{ msg }} </ h1 >
< h1 >{{ datas. name}} </ h1 >
</ div >
</ template >

< script >
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
datas:{}
}
},
mounted(){
this. $fetch( 'http://localhost:8080/static/data.json')
. then(( response) => {
console. log( response)
this. datas = response
})
},
}

猜你喜欢

转载自blog.csdn.net/weixin_38641550/article/details/80753111