修复未登录时 API 返回 HTML 导致期权链 JSON 解析失败。

API 统一返回 401 JSON,并改进前端非 JSON 错误提示。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-10-01 11:51:13 +08:00
parent ed9fd05a84
commit e7a4934068
3 changed files with 25 additions and 2 deletions
+9
View File
@@ -5157,6 +5157,15 @@ def login_required(f):
def decorated(*args, **kwargs): def decorated(*args, **kwargs):
if AUTH_DISABLED or bool(session.get("logged_in")): if AUTH_DISABLED or bool(session.get("logged_in")):
return f(*args, **kwargs) return f(*args, **kwargs)
# API 必须返回 JSON,否则前端 r.json() 会报 Unexpected token...
path = request.path or ""
wants_json = (
path.startswith("/api/")
or (request.headers.get("X-Requested-With") or "").lower() == "xmlhttprequest"
or "application/json" in (request.headers.get("Accept") or "")
)
if wants_json:
return jsonify({"ok": False, "msg": "未登录或会话过期,请重新登录"}), 401
return redirect("/login") return redirect("/login")
return decorated return decorated
+15 -1
View File
@@ -78,7 +78,21 @@
async function apiJson(url, opts) { async function apiJson(url, opts) {
const r = await fetch(url, Object.assign({ credentials: "same-origin" }, opts || {})); const r = await fetch(url, Object.assign({ credentials: "same-origin" }, opts || {}));
return r.json(); const text = await r.text();
let data = null;
try {
data = text ? JSON.parse(text) : null;
} catch (e) {
if (/\/login/i.test(r.url || "") || /^\s*<!doctype/i.test(text) || /^\s*<html/i.test(text)) {
throw new Error("未登录或会话过期,请从中控重新打开工作台");
}
const snip = String(text || "").replace(/\s+/g, " ").slice(0, 100);
throw new Error("接口返回非 JSON(HTTP " + r.status + ")" + (snip ? ": " + snip : ""));
}
if (r.status === 401) {
throw new Error((data && data.msg) || "未登录或会话过期,请从中控重新打开工作台");
}
return data;
} }
function orderPanel() { function orderPanel() {
+1 -1
View File
@@ -355,4 +355,4 @@
</div> </div>
</div> </div>
<script src="/static/options_expiry_countdown.js?v=1"></script> <script src="/static/options_expiry_countdown.js?v=1"></script>
<script src="/static/options_panel.js?v=65"></script> <script src="/static/options_panel.js?v=66"></script>