1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- const baseURL = 'https://api.example.com'; // 替换为您的实际API地址
- // 请求拦截器
- const requestInterceptor = (config) => {
- // 在这里添加token等认证信息
- const token = uni.getStorageSync('token');
- if (token) {
- config.header = {
- ...config.header,
- 'Authorization': `Bearer ${token}`
- };
- }
- return config;
- };
- // 响应拦截器
- const responseInterceptor = (response) => {
- // 在这里处理响应数据
- if (response.statusCode === 200) {
- return response.data;
- }
- // 处理错误情况
- uni.showToast({
- title: response.data.message || '请求失败',
- icon: 'none'
- });
- return Promise.reject(response);
- };
- // 封装请求方法
- const request = (options) => {
- const config = requestInterceptor({
- ...options,
- url: `${baseURL}${options.url}`,
- header: {
- 'Content-Type': 'application/json',
- ...options.header
- }
- });
- return new Promise((resolve, reject) => {
- uni.request({
- ...config,
- success: (res) => {
- resolve(responseInterceptor(res));
- },
- fail: (err) => {
- uni.showToast({
- title: '网络请求失败',
- icon: 'none'
- });
- reject(err);
- }
- });
- });
- };
- // 导出请求方法
- export default {
- get: (url, data = {}, options = {}) => {
- return request({
- url,
- data,
- method: 'GET',
- ...options
- });
- },
-
- post: (url, data = {}, options = {}) => {
- return request({
- url,
- data,
- method: 'POST',
- ...options
- });
- },
-
- put: (url, data = {}, options = {}) => {
- return request({
- url,
- data,
- method: 'PUT',
- ...options
- });
- },
-
- delete: (url, data = {}, options = {}) => {
- return request({
- url,
- data,
- method: 'DELETE',
- ...options
- });
- }
- };
|