一、新建request.js
/*
* 功能:小程序仿 axios 的请求封装
*/
export default class Request {
// 配置项
configure = {
baseURL: '', // 请求url地址
header: {
'content-type': 'application/json;charset=utf-8'
}, // header
method: 'GET', // 请求的类型,支持get,post,put,delete等
dataType: 'json', // 返回的数据格式,默认json
responseType: 'text', // 响应的数据格式,默认text
data: {}, // 传参
timeout: 3 * 1000, // 请求超时时间
}
// 拦截器
interceptors = {
request: {
use: (configCb) => {
if (configCb) this.interceptors.request.before = configCb;
},
before: (configCb => {
return configCb;
})
},
response: {
use: (successCb, errorCb) => {
if (successCb) this.interceptors.response.success = successCb;
if (errorCb) this.interceptors.response.error = errorCb;
},
success: (successCb => successCb),
error: (errorCb => errorCb),
}
}
// 构造器
constructor(props) {
this.configure = Object.assign(this.configure, props);
}
// 提供create方法注入参数
static create(configure = {}) {
return new this(configure);
}
// 支持以下 http 请求方式,如果修改请求类型,设置 header 的 content-type 覆盖默认的即可
get(url, data = {}, header = { 'content-type': 'application/json;charset=utf-8' }) {
return this.request('GET', url, data, header);
}
post(url, data = {}, header = { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' }) {
return this.request('POST', url, data, header);
}
put(url, data = {}, header = {}) {
return this.request('PUT', url, data, header);
}
delete(url, data = {}, header = {}) {
return this.request('DELETE', url, data, header);
}
head(url, data = {}, header = {}) {
return this.request('HEAD', url, data, header);
}
options(url, data = {}, header = {}) {
return this.request('OPTIONS', url, data, header);
}
trace(url, data = {}, header = {}) {
return this.request('TRACE', url, data, header);
}
connect(url, data = {}, header = {}) {
return this.request('CONNECT', url, data, header);
}
// 判断是否传的url中带有http前缀,有则不会拼加baseUrl
isProtocol(url) {
return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
}
// request封装
request(method = '', url = '', data = {}, header = {}) {
// 参数配置
url = this.isProtocol(url) ? url : this.configure.baseURL + url;
header = { ...this.configure.header, ...header };
// 设置传递的最新数据
this.configure.data = data;
this.configure.header = header;
this.configure.method = method;
// 请求拦截
this.interceptors.request.before({ ...this.configure });
// request请求
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: data,
header: header,
dataType: this.configure.dataType || 'json',
responseType: this.configure.responseType || 'text',
method: method,
success: res => {
// 成功拦截器回调
if (res && res.statusCode == 200) {
this.interceptors.response.success(res);
resolve(res);
} else {
// 错误拦截器回调
this.interceptors.response.error(res);
reject(res);
}
},
fail: err => {
// 错误拦截器回调
this.interceptors.response.error(err);
reject(err);
}
})
})
}
}
二、创建http.js文件
import request from 'request.js'
// 创建request实例
const service = request.create({
baseURL: 'http://localhost:8080', // 请求后台api的地址,可以抽离出去
})
// request拦截
service.interceptors.request.use(config => {
// 每次请求都可以在header中带参数
config.header['token'] = 1234;
config.header['my_sessionid'] = 1234;
console.log('request-config:', config);
return config;
})
// response拦截
service.interceptors.response.use(response => {
console.log('response-success:', response);
return response;
}, error => {
console.log('response-error:', error);
return Promise.reject(error);
})
// 导出
export default service;
三、在小程序js中使用
先引入http.js
import http from 'http.js'
调用http实例中的方法,有get,post, put,delete等
http.post('/api/user/getList', {
name: '小明'
}).then(res => {
console.log('成功数据:', res.data);
}).catch(error => {
console.log('失败数据:', error);
})
附上小程序基础框架的目录结构图