1.封装wx.request
import config from "./config";
const baseUrl = config.baseUrl;
// 封装get请求
const get = (url, data) => {
let header = { "content-type": "application/json" };
let tokenKey = wx.getStorageSync("tokenKey");
if (tokenKey) {
header.tokenKey = tokenKey;
}
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
data: data,
header,
success(res) {
if (res.statusCode == 200) {
if (res.data.code == -1) {
//处理登录过期
}
resolve(res.data);
} else {
//此处处理非200状态码的结果
}
},
error(e) {
reject(e);
}
});
});
};
// 封装post请求
const post = (url, data) => {
let header = { "content-type": "application/json" };
let tokenKey = wx.getStorageSync("tokenKey");
if (tokenKey) {
header.tokenKey = tokenKey;
}
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
data: data,
method: "POST",
header,
success(res) {
if (res.statusCode == 200) {
if (res.data.code == -1) {
//处理登录过期
}
resolve(res.data);
} else {
//此处处理非200状态码的结果
}
},
error(e) {
reject(e);
}
});
});
};
// 封装上传文件
const uploadFiles = data => {
let header = {
tokenKey: wx.getStorageSync("tokenKey")
};
const { url, filePath, name, formData } = data;
return new Promise((resolve, reject) => {
wx.uploadFile({
url: baseUrl + url,
filePath,
name,
formData,
header,
success(res) {
const data = JSON.parse(res.data);
resolve(data);
},
error(err) {
reject(err);
}
});
});
};
const http = { get, post, uploadFiles };
module.exports = http;
2.封装flyio
其中wx.js文件在flyio的github上面下载即可
①
import FlyWX from './wx.js'
import config from "../../config/index"
const Flyio = new FlyWX()
class HttpRequest {
constructor() {
this.defaultConfig = {
baseURL: config.baseUrl[config.NODE_ENV],
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
Flyio.config = Object.assign({}, Flyio.config, this.defaultConfig)
this.interceptors(Flyio)
return Flyio
}
// 拦截器
interceptors(instance) {
// 请求拦截
instance.interceptors.request.use(request => {
return request
}, error => {
return Promise.reject(error)
});
// 响应拦截
instance.interceptors.response.use(response => {
const { data } = response
return data
}, error => {
// 处理错误请求响应
});
}
}
export default new HttpRequest()
②使用的时候在api.js中引入,如
import http from '../libs/request/index'
const reqGoodsList = (data) => http.request(
"api/get-goods-list",
data
);
export default {
reqGoodsList
}