1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- // request.js
- import Notify from '../miniprogram_npm/@vant/weapp/notify/notify';
- // 配置项
- const token = wx.getStorageSync('token')
- const config = {
- baseURL: 'http://192.168.1.16:8901', // 基础URL
- timeout: 30000, // 超时时间(单位ms)
- header: {
- 'content-type': 'application/json', // 默认请求头
- "token":token
- // 其他全局请求头...
- },
- // 其他全局配置...
- };
-
- // 封装请求方法
- function request(url, method = 'GET', data = {}, header = {}) {
- return new Promise((resolve, reject) => {
- wx.request({
- url: config.baseURL + url,
- method: method.toUpperCase(),
- data: method === 'GET' ? {} : data, // GET请求时将data置为空对象
- header: {
- ...config.header,
- ...header,
- },
- timeout: config.timeout,
- success: function(res){
- // 根据业务逻辑处理成功响应
- if (res.data && res.data.code === 200) { // 假设服务器返回code为200表示成功
- resolve(res.data);
- } else {
- switch(res.data.code){
- case 401:
- Notify({ type: 'danger', message: '未登录' });
- wx.navigateTo({
- url: '/pages/login/login',
- })
- break;
- default:
- Notify({ type: 'danger', message: '请求失败' });
-
- }
- // wx.showToast({
- // title: '请求失败',
- // icon: 'error',
- // duration: 2000
- // })
- reject(res.data.message || '未知错误');
- }
- },
- fail: function(error) {
- console.log(error)
-
- // 处理请求失败
- // wx.showToast({
- // title: '请求失败',
- // icon: 'error',
- // duration: 2000
- // })
- Notify({ type: 'danger', message: '请求失败' });
- reject(error);
- },
- });
- });
- }
-
- // 导出请求方法
- module.exports = {
- get: (url, data, header) => request(url, 'GET', data, header),
- post: (url, data, header) => request(url, 'POST', data, header),
- // 可以继续添加其他方法,如put, delete等
- // ...
- };
|