使用 JavaScript 的 fetch 实现登录功能详解📥

235 阅读3分钟

在现代前端开发中,与后端 API 交互是构建动态网页的重要组成部分。通过使用 JavaScript 的 fetch API,我们可以轻松地向服务器发送请求并处理响应数据。本文将以一个用户登录的场景为例,详细解析如何使用 fetch 发起 POST 请求,并处理返回的数据。

📥 用户输入:获取用户名和密码

在 HTML 页面中,我们通常会提供一个表单供用户输入用户名和密码:

<form id="loginForm">
  <input type="text" id="username" placeholder="用户名" />
  <input type="password" id="password" placeholder="密码" />
  <button type="submit">登录</button>
</form>

当用户点击“登录”按钮提交数据时,我们需要阻止浏览器默认的提交行为,并获取用户输入的内容

document.getElementById('loginForm').addEventListener('submit', async function (e) {
  e.preventDefault(); // 阻止默认提交行为

  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
});

🚀 使用 fetch 发送 POST 请求

接下来,我们将使用 fetch/login 接口发送 POST 请求,将用户的用户名和密码传给服务器

const response = await fetch('/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username, password })
});

代码解析:

method:'POST' 指定请求方式为POST,常用于提交数据,有请求体携带数据

headers 请求头,告诉服务器发送的是JSON数据

body 请求体,将用户提交的实际数据 JSON对象 转为 JSON字符串格式,因为HTTP协议只能传输字符串,所以要序列化。

例如:

{ username: "tom", password: "123456" }
"{"username":"tom","password":"123456"}"

📤 处理服务器响应

发送完请求后,我们需要等待服务器返回结果,并将结果解析为 JavaScript 对象以便后续处理:

const data = await response.json();

假设服务器返回如下结构化的 JSON 数据:

{
  "success": true,
  "message": "登录成功",
  "user": {
    "id": 1,
    "name": "Tom"
  }
}

我们就可以根据这个结果进行判断并作出相应操作:

if (data.success) {
  alert('登录成功!');
  console.log('欢迎回来,' + data.user.name);
} else {
  alert('登录失败:' + data.message);
}

🧪 完整示例代码

以下是完整的 HTML 和 JavaScript 示例代码:

<form id="loginForm">
  <input type="text" id="username" placeholder="用户名" />
  <input type="password" id="password" placeholder="密码" />
  <button type="submit">登录</button>
</form>

<script>
document.getElementById('loginForm').addEventListener('submit', async function (e) {
  e.preventDefault(); // 阻止默认提交行为

  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  const response = await fetch('/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password })
  });

  const data = await response.json();

  if (data.success) {
    alert('登录成功!');
    console.log('欢迎回来,' + data.user.name);
  } else {
    alert('登录失败:' + data.message);
  }
});
</script>

🧠 总结

通过上面的例子,我们了解了如何使用 fetch 来实现一个基本的登录功能。整个流程可以总结为以下几步:

步骤内容
1. 获取用户输入从表单中提取用户名和密码
2. 发起 POST 请求使用 fetch 提交数据到 /login 接口
3. 设置请求头声明发送的是 JSON 格式数据
4. 序列化数据使用 JSON.stringify() 将对象转为字符串
5. 等待响应异步等待服务器返回结果
6. 解析响应使用 .json() 方法将返回数据转为 JS 对象
7. 处理逻辑根据返回结果执行相应的业务逻辑