新建一个http.js文件,粘贴以下,
(根据需求修改以下参数,引入地址以及参数API_URL,token)
import env from '../env'
// ( 上面引入 API_URL = 'https://m.ylnhome.com/api';)
import axios from 'axios'
//(引入axios)
import appUser from './login'
//(需要取token)
class Axios2 {
constructor(config) {
this.config = Object.assign({
timeout: 300,
dataType: 'json'
}, config);
//拦截器对象
this.interceptor = {
reqQueue: [],
resQueue: [],
request: function(configFunc) {
this.reqQueue.push(configFunc)
},
response: function(successFunc, failFunc) {
this.resQueue.push(successFunc, failFunc)
}
};
//添加GET,POST.PUT.DELETE四种方法
['POST', 'GET', 'PUT', 'DELETE'].reduce((pre, method) => {
pre[method] = function(url, data) {
return this.request.call(this, Object.assign(this.config || {}, {
url,
method: method,
data: data || {}
}))
}
return pre;
}, this);
}
request(conf) {
//执行request拦截器
let config = this.interceptor.reqQueue[0].call(this, conf);
var data = config.data
return new Promise((resolve, reject) => {
if (config.method == 'POST') {
wx.request({
method: config.method,
url: env.API_URL + config.url + '?token=' + appUser.token,
data: {...data } || {},
header: config.header || {
'content-type': 'application/json'
},
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
}
})
} else {
wx.request({
method: config.method,
url: env.API_URL + config.url,
data: {...data, token: appUser.token } || {},
header: config.header || {
'content-type': 'application/json'
},
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
}
})
}
})
//响应拦截器
.then(this.interceptor.resQueue[0] || (res => Promise.resolve(res))) //ok response
.catch(this.interceptor.resQueue[1] || (err => Promise.reject(err))); // fail response
}
};
let axios2 = new Axios2();
//请求拦截器
axios2.interceptor.request(function(config) {
console.log('---------请求拦截器-------');
return config || {};
});
axios2.interceptor.response(res => {
console.log('成功响应拦截')
return Promise.resolve(res);
}, err => {
console.log('失败响应拦截')
return Promise.reject(err)
});
export default axios2
在其他页面使用时
1.GET
<script>
import axios2 from "@/utils/http2";
export default class SelectBox extends wepy.component {
methods = {
aa(){
axios2.GET("/store/storeConfig/getShowTheArticle", {
current: 1,
pageSize: 10,
})
.then(res => {
if (res.code == 1) {
console.log(res,''数据")
}
})
}
}
}
2.POST
axios2.POST("/store/articleParticulars/update", {
pageviews: this.weishipinglist[e.detail.current].pageviews,
id: current_viewing.id
})
.then(res => {
if (res.code == 1) {
}
})