封装请求的方法,完成简易的问题解答页面
This commit is contained in:
@@ -126,3 +126,42 @@ function debounce(fn, interval) {
|
||||
}, gapTime);
|
||||
}
|
||||
}
|
||||
export const showLoading = async (options = {}) => {
|
||||
const { title } = options;
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.showLoading({
|
||||
title: title || '加载中',
|
||||
success: () => {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
export const hideLoading = async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.hideLoading({
|
||||
success: () => {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export const alertInfo = (message) => {
|
||||
return wx.showToast({
|
||||
title: message,
|
||||
icon: 'none',
|
||||
})
|
||||
}
|
||||
export const alertSuccess = (message) => {
|
||||
return wx.showToast({
|
||||
title: message,
|
||||
icon: 'success'
|
||||
})
|
||||
}
|
||||
export const alertError = (message) => {
|
||||
return wx.showToast({
|
||||
title: message,
|
||||
icon: 'error'
|
||||
})
|
||||
}
|
154
utils/request.js
Normal file
154
utils/request.js
Normal file
@@ -0,0 +1,154 @@
|
||||
import { alertError, alertInfo, getGlobalData } from './index.js';
|
||||
|
||||
// 普通函数 -> Promise函数
|
||||
const promisify = (api) => {
|
||||
return (options, ...params) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
|
||||
});
|
||||
}
|
||||
}
|
||||
// 获取全局变量
|
||||
const globalData = getGlobalData();
|
||||
const { api } = globalData;
|
||||
const RAW_SERVER = api;
|
||||
const SERVER = api;
|
||||
const ok = 200;
|
||||
|
||||
const requestWithoutCookie = promisify(wx.request);
|
||||
|
||||
// 考虑了Cookie的请求
|
||||
const request = async function (options) {
|
||||
let token = wx.getStorageSync('token');
|
||||
options.header = {
|
||||
Accept: 'application/json',
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
"authorization": token
|
||||
};
|
||||
let response;
|
||||
try {
|
||||
response = await requestWithoutCookie(options);
|
||||
// 服务器没有返回200直接报错
|
||||
if (!response || response.statusCode !== 200) {
|
||||
alertError(response?.data?.message || "发生错误,请稍后重试")
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理cookie
|
||||
const setCookie = response.header['set-cookie'] || response.header['Set-Cookie'];
|
||||
if (setCookie) {
|
||||
const cookieMap = {};
|
||||
|
||||
if (localCookieString) {
|
||||
const localCookies = localCookieString.split('; ');
|
||||
|
||||
for (const localCookie of localCookies) {
|
||||
const matchResult = localCookie.match(/^([^=]+)=(.+)/);
|
||||
cookieMap[matchResult[1]] = matchResult[2];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const matchResultSet = setCookie.match(/^([^=]+)=([^;]+);/);
|
||||
cookieMap[matchResultSet[1]] = matchResultSet[2];
|
||||
|
||||
const cookies = [];
|
||||
for (const name in cookieMap) {
|
||||
if (!{}.hasOwnProperty.call(cookieMap, name)) {
|
||||
continue;
|
||||
}
|
||||
const value = cookieMap[name];
|
||||
cookies.push(`${name}=${value}`);
|
||||
}
|
||||
|
||||
await setStorage({
|
||||
key: 'cookies',
|
||||
data: cookies.join('; ')
|
||||
});
|
||||
}
|
||||
} catch(err) {
|
||||
alertInfo(err.errMsg)
|
||||
}
|
||||
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// 处理返回结果,默认直接返回数据
|
||||
const parseResponse = function (response) {
|
||||
if (!response) {
|
||||
alertError("服务异常")
|
||||
return
|
||||
}
|
||||
const { code: statusCode } = response.data;
|
||||
if (statusCode === 401) {
|
||||
wx.redirectTo({
|
||||
url: '/pages/login/index',
|
||||
})
|
||||
return { code: 1, message: '未登录状态' }
|
||||
}
|
||||
if (statusCode === 404) {
|
||||
return { code: 1, message: "服务故障" }
|
||||
}
|
||||
if (500 <= statusCode < 600) {
|
||||
return { code: 1, message: "服务错误" }
|
||||
}
|
||||
|
||||
if (response.data.code !== 0) {
|
||||
|
||||
}
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// GET请求
|
||||
const GET = async function (uri) {
|
||||
const response = await request({
|
||||
url: `${SERVER}${uri}`,
|
||||
method: 'GET'
|
||||
});
|
||||
|
||||
return parseResponse(response);
|
||||
};
|
||||
|
||||
// 创建、更新和删除请求
|
||||
const CUD = async function (method, uri, data = null) {
|
||||
|
||||
// 没有CSRF Token就前往获取
|
||||
|
||||
// 请求参数
|
||||
const options = {
|
||||
url: `${SERVER}${uri}`,
|
||||
method,
|
||||
};
|
||||
if (data) {
|
||||
options.data = data;
|
||||
}
|
||||
const response = await request(options);
|
||||
return parseResponse(response);
|
||||
};
|
||||
|
||||
// 创建请求
|
||||
const POST = async function (uri, data) {
|
||||
return await CUD('POST', uri, data);
|
||||
}
|
||||
|
||||
// 修改请求
|
||||
const PUT = async function (uri, data) {
|
||||
return await CUD('PUT', uri, data);
|
||||
}
|
||||
|
||||
// 删除请求
|
||||
const DELETE = async function (uri, data) {
|
||||
return await CUD('DELETE', uri, data);
|
||||
}
|
||||
|
||||
export default {
|
||||
GET,
|
||||
POST,
|
||||
PUT,
|
||||
DELETE,
|
||||
SERVER,
|
||||
RAW_SERVER,
|
||||
api
|
||||
};
|
Reference in New Issue
Block a user