feat: 小程序连接服务器IP + 同步未提交开发
- miniprogram/config.js: BASE_URL 指向 http://192.227.237.8:3001 - 动作标题中文化(nameZh),搜索匹配 name/nameZh/nameEn - 新增计划/收藏/我的 等页面与组件 - 后端 Docker 化(Dockerfile/.dockerignore)与翻译脚本 - .gitignore 补充 .DS_Store
This commit is contained in:
@@ -1,22 +1,37 @@
|
||||
// 统一的网络请求封装:所有请求都经过此包装器。
|
||||
// 后端为公开 API,无需鉴权头;失败时统一 toast 提示。
|
||||
// 受保护接口自动携带 Authorization: Bearer <token>;遇到 401 时由注册的
|
||||
// 未授权处理器(通常是自动重新登录)处理一次,然后重试原请求。
|
||||
const { BASE_URL } = require('../config');
|
||||
|
||||
function request({ url, method = 'GET', data = {} }) {
|
||||
let unauthorizedHandler = null;
|
||||
|
||||
// 注册「未授权」处理回调(由 auth 模块注入,用于自动重新登录)
|
||||
function setUnauthorizedHandler(fn) {
|
||||
unauthorizedHandler = fn;
|
||||
}
|
||||
|
||||
function request({ url, method = 'GET', data = {}, _retry = false }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = wx.getStorageSync('access_token');
|
||||
wx.request({
|
||||
url: BASE_URL + url,
|
||||
method,
|
||||
data,
|
||||
header: { 'content-type': 'application/json' },
|
||||
header: {
|
||||
'content-type': 'application/json',
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {})
|
||||
},
|
||||
success(res) {
|
||||
// 401:尝试一次自动重新登录后重试
|
||||
if (res.statusCode === 401 && !_retry && unauthorizedHandler) {
|
||||
return unauthorizedHandler()
|
||||
.then((t) => (t ? resolve(request({ url, method, data, _retry: true })) : reject(res)))
|
||||
.catch(() => reject(res));
|
||||
}
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
resolve(res.data);
|
||||
} else {
|
||||
wx.showToast({
|
||||
title: '请求失败 (' + res.statusCode + ')',
|
||||
icon: 'none'
|
||||
});
|
||||
wx.showToast({ title: '请求失败 (' + res.statusCode + ')', icon: 'none' });
|
||||
reject(res);
|
||||
}
|
||||
},
|
||||
@@ -28,4 +43,4 @@ function request({ url, method = 'GET', data = {} }) {
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { request };
|
||||
module.exports = { request, setUnauthorizedHandler };
|
||||
|
||||
Reference in New Issue
Block a user