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

Express后端+HTML前端:登录请求后如何留页处理返回结果

解决登录页面跳转问题的修改方案

问题核心是表单默认提交行为会触发页面跳转,且你的fetch请求是GET方法(和接口的POST不匹配),导致逻辑没按预期执行,按以下步骤修改:

1. 完善HTML表单结构

提交按钮需要放在<form>标签内,给表单添加id方便后续操作:

<form id="loginForm">
  <input type="email" name="email" placeholder="邮箱" required>
  <input type="password" name="password" placeholder="密码" required>
  <input type="submit" value="Log In" id="loginbutton">
</form>

2. 修改JS逻辑,实现无跳转登录

替换你原有的main函数,改成监听表单提交事件:

// 监听表单提交事件
document.getElementById('loginForm').addEventListener('submit', async function(e) {
  // 阻止表单默认跳转行为,让页面停留在当前页
  e.preventDefault();

  // 收集表单里的邮箱和密码
  const email = this.querySelector('[name="email"]').value;
  const password = this.querySelector('[name="password"]').value;

  try {
    // 发送POST请求匹配后端接口
    const response = await fetch('http://localhost:4000/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      // 把数据转成JSON格式传给后端
      body: JSON.stringify({ email, password })
    });

    const result = await response.json();
    // 处理后端返回的结果
    processObject(result);
  } catch (error) {
    console.error('登录请求出错:', error);
    alert('网络异常,请稍后重试');
  }
});

function processObject({ nouser, wrongpassword, username, accessToken, refreshToken }) {
  if (nouser) {
    // 账号未注册,提示跳转注册页
    if (confirm('该账号未注册,是否前往注册?')) {
      window.location.href = '/register'; // 替换为你的注册页地址
    }
  } else if (wrongpassword) {
    // 密码错误提示
    alert('密码错误,请重新输入');
  } else {
    // 登录成功,存储token并跳转到用户页
    localStorage.setItem('accessToken', accessToken);
    localStorage.setItem('refreshToken', refreshToken);
    window.location.href = '/user'; // 替换为你的用户页地址
  }
}

关键修改点说明

  • 阻止默认行为:通过e.preventDefault()取消表单提交后的页面跳转,确保页面停留在index.html执行后续逻辑
  • 匹配请求方法:后端接口是POST /login,所以fetch必须使用method: 'POST'才能正确调用接口
  • 传递正确数据:把邮箱和密码转成JSON格式放在请求体内,和后端req.body.email、req.body.password的取值对应
  • 异常处理:增加try/catch捕获网络错误,避免请求失败时无提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:23:34