Files
for-test/frontend/js/api.js
T
nancy cf3b25d6c5 feat: 商户端登录/注册模块 - HTML原型+前端+后端
基于飞书 PRD《【登陆/注册】》实现:
- prototype/: 可交互 HTML 原型(内置 Mock,含三语切换)
- frontend/: 正式前端(原生 HTML/CSS/JS,调用后端 API)
- backend/: Node.js 零依赖后端(验证码冷却/静默注册/IP冻结)
- design/: 飞书白板设计图导出
2026-10-17 23:22:10 +08:00

40 lines
1.4 KiB
JavaScript

/* 后端 API 封装:统一请求、错误码处理 */
const API_BASE = location.hostname === 'localhost' || location.hostname === '127.0.0.1'
? 'http://localhost:3000/api' : '/api';
const CODE = {
OK: 0,
BAD_REQUEST: 400,
INVALID_CREDENTIALS: 1001, // 无效登录信息
IP_FROZEN: 1002, // 同 IP 连续错误过多,登录权限暂停
CODE_INVALID: 1003, // 验证码错误/过期
SEND_TOO_FREQUENT: 1004 // 验证码发送冷却中
};
async function api(path, data) {
let res;
try {
res = await fetch(API_BASE + path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data || {})
});
} catch (e) {
throw { code: -1, message: 'NETWORK' };
}
const json = await res.json().catch(() => ({ code: -1, message: 'NETWORK' }));
if (!res.ok || json.code !== CODE.OK) throw json;
return json.data;
}
const Api = {
/** 发送验证码 type: phone | email */
sendCode: (type, target) => api('/captcha/send', { type, target }),
/** 验证码登录(未注册静默注册) */
loginByCode: (type, target, code) => api('/login/verify-code', { type, target, code }),
/** 账号密码登录(子账号格式:子ID@主ID) */
loginByPassword: (account, password) => api('/login/password', { account, password }),
/** 忘记密码 */
forgotPassword: (account) => api('/password/forgot', { account })
};