修复未登录时 API 返回 HTML 导致期权链 JSON 解析失败。
API 统一返回 401 JSON,并改进前端非 JSON 错误提示。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -5157,6 +5157,15 @@ def login_required(f):
|
||||
def decorated(*args, **kwargs):
|
||||
if AUTH_DISABLED or bool(session.get("logged_in")):
|
||||
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 decorated
|
||||
|
||||
|
||||
@@ -78,7 +78,21 @@
|
||||
|
||||
async function apiJson(url, 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() {
|
||||
|
||||
@@ -355,4 +355,4 @@
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
Reference in New Issue
Block a user