axios安装
npm install axios --save
首先在src目录下创建axios文件夹,然后创建index.js和fetch.js两个文件。
fetch.js文件代码如下:
import axiosfrom 'axios'
//定义fetch函数,config为配置
export function fetch(config){
//返回promise对象
return new Promise((resolve,reject) =>{
//创建axios实例,把基本的配置放进去
const instance = axios.create({
//定义请求文件类型
headers:{
'Content-Type':'application/json',
},
timeout:5000,
//定义请求根目录
baseURL:'/api/' //这里我们解决了跨域设置了代理
});
//请求成功后执行的函数
instance(config).then(res =>{
console.log(res);
resolve(res);
//失败后执行的函数
}).catch(err => {
console.log(err);
reject(err);
})
});
}
index.js 文件代码如下:
//引入fetch.js文件
import {fetch }from './fetch'
//定义获取数据的函数getData(),其中url,type,data对应fetch(config)中的config
export function getData(url,type,data) {
//如果type为空,默认为post方法,也可以自己改成get
if(type==='')
type ='get';
return fetch({
//这里的url为baseURL下接口地址,如baseURL为'www.baidu.com',接口地址为'www.baidu.com/api/getdata',那么url里就写'api/getdata'
url: url,
method: type,
data: data,
})
}
这样基本的功能就有了,然后在页面上使用的代码如下(假设页面为home.vue,在src/pages目录下):
import{ getData }from'./../axios'
getData('wechat/topayment?paymentCode=SDBWG95174', '').then(res => {
console.log(res);
}, err => {
console.log(err);
})
设置代理
proxyTable: {
'/api': {
target:'http://192.168.1.16:9010',
changeOrigin:true,
pathRewrite: {
'^/api':''
}
}
},