一、封装request请求
因为我把所有项目中的接口也封装到了一个文件中,所以我建了一个services的文件夹,在下面建了一个request.js
在这个里面做了请求拦截器和响应拦截器,
javascript
const apiConfig = require('../config/baseUrl.js');
class httpClient {
prefixUrl = '';
constructor(prefixUrl = '') {
this.prefixUrl = prefixUrl
}
interceptors = {
// 请求拦截器
request: (params) => {
if (params.showLoading) {
// TODO: 封装loading
tt.showLoading({
"title": "加载中...",
"mask": true,
});
}
// 处理请求数据,如添加Header信息等,
const config = {
...params,
url: apiConfig.BASE_URL + this.prefixUrl + params.url,
header: {
...params.header,
'Content-type': 'application/json',
//TODO: 后端需要的字段
// 'Access-Token': tt.getStorageSync('login.user.xxx')
},
timeout: 60000, // 超时时长,小程序默认是 1 分钟
};
if (config.method === 'GET') {
config.url += '?' + Object.keys(config.data).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(config.data[key])}`).join('&');
}
return config;
},
// 响应拦截器
response: (response) => {
console.log('response', response)
if (response.config.showLoading) {
tt.hideLoading();
}
//TODO: 错误信息处理
if (response.data.code && response.data.code !== 0 && response.data.code !== 200) {
tt.showToast({
title: response.data.message,
duration: 2000,
icon: "none",
mask: false
});
return Promise.reject(response);
}
return response.data;
}
}
request(config) {
config = this.interceptors.request(config)
// 网络请求
return new Promise((resolve, reject) => {
tt.request({
...config,
success: (res) => {
const mergeRes = Object.assign({}, res, {config})
resolve(this.interceptors.response(mergeRes))
},
fail: (err) => {
const mergeErr = Object.assign({}, err, {config})
reject(this.interceptors.response(mergeErr))
},
});
});
}
get(url, data = {}, config = {}, loading = true) {
return this.request(Object.assign({ url, data, method: 'GET', showLoading: loading }, config))
}
post(url, data = {}, config = {}, loading = true) {
return this.request(Object.assign({ url, data, method: 'POST', showLoading: loading }, config))
}
put(url, data = {}, config = {}, loading = true) {
return this.request(Object.assign({ url, data, method: 'PUT', showLoading: loading }, config))
}
delete(url, data = {}, config = {}, loading = true) {
return this.request(Object.assign({ url, data, method: 'DELETE', showLoading: loading }, config))
}
}
module.exports = httpClient;
2、封装对应的 api 文件
在service的文件夹下面建了一个api.js【因为目前这个小程序页面比较少,暂定把所有接口写在同一个文件夹下】
javascript
const httpClient = require('./request.js');
class ApiManager extends httpClient {
constructor(){
super('/api');
}
login(data) {
return this.post('/login', data);
}
getData(data, config) {
return this.get('/train_types', data, config);
}
}
module.exports = new ApiManager();
3. 管理所有地址
javascript
module.exports = {
BASE_URL: 'http://192.168.2.68:1911',
}
4. 使用
javascript
const loginResponse = await ApiManager.login({
user_name: 'admin',
password:'hsradmin2022'
})
console.log('loginResponse', loginResponse)
const response = await ApiManager.getData({}, {
header: {
'Access-Token': loginResponse.data.access_token,
},
});
this.setData({
list: response.data.list
})
console.log(response.data);
参考链接
https://www.npmjs.com/package/mina-request?activeTab=code
官方文档
https://open.feishu.cn/document/uAjLw4CM/uYjL24iN/block/api/network/request