You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

登录验证后重定向页面引发JSON解析语法错误的问题求助

登录验证重定向报错的解决方案

错误原因

当服务端执行res.redirect()时,会返回跳转目标页面的HTML内容,但前端代码强制用response.json()解析该HTML——HTML并非合法JSON格式,因此抛出Unexpected token '<'的语法错误。

解决方案

方案一:前端根据响应类型处理跳转

修改前端fetch逻辑,先判断响应是否为HTML,是则直接跳转,否则解析JSON:

fetch(`/login?username=${username}&password=${password}`)
  .then((response) => {
    if (response.headers.get('content-type').includes('text/html')) {
      window.location.href = response.url;
      return;
    }
    return response.json();
  })
  .then((data) => {
    if (data) {
      alert(data.message === "Login successful" ? "Login successful" : "Invalid username or password");
      document.getElementById("login-username").value = "";
      document.getElementById("login-password").value = "";
    }
  })
  .catch((error) => {
    console.error("Error:", error);
  });

方案二:服务端返回JSON,前端主动跳转(更推荐)

服务端不直接重定向,返回包含跳转地址的JSON,由前端控制跳转:

  • 服务端代码修改:
if (results.length > 0) {
  res.json({ message: "Login successful", redirectUrl: "/webpages/codingspace/coding.html" });
} else {
  res.json({ message: "Invalid username or password" });
}
  • 前端代码修改:
.then((data) => {
  if (data.message === "Login successful") {
    alert("Login successful");
    window.location.href = data.redirectUrl;
  } else {
    alert("Invalid username or password");
  }
  document.getElementById("login-username").value = "";
  document.getElementById("login-password").value = "";
})

重要安全优化

登录请求禁止使用GET方法——用户名和密码会暴露在URL中,存在严重安全隐患。建议改用POST方法:

  • 服务端POST接口:
app.post("/login", (req, res) => {
  const { username, password } = req.body;
  const sql = "SELECT * FROM authdetails WHERE username = ? AND password = ?";
  db.query(sql, [username, password], (err, results) => {
    if (err) {
      console.error("Error searching for user:", err);
      res.status(500).json({ error: "Database error" });
    } else {
      if (results.length > 0) {
        res.json({ message: "Login successful", redirectUrl: "/webpages/codingspace/coding.html" });
      } else {
        res.json({ message: "Invalid username or password" });
      }
    }
  });
});
  • 前端POST请求:
fetch("/login", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ username, password }),
})
.then((response) => response.json())
.then((data) => {
  if (data.message === "Login successful") {
    alert("Login successful");
    window.location.href = data.redirectUrl;
  } else {
    alert("Invalid username or password");
  }
  document.getElementById("login-username").value = "";
  document.getElementById("login-password").value = "";
})
.catch((error) => {
  console.error("Error:", error);
});

内容的提问来源于stack exchange,提问作者CodeBlaze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:46:05