Home  >  Article  >  Web Front-end  >  How to use JavaScript to implement login functionality

How to use JavaScript to implement login functionality

PHPz
PHPzOriginal
2023-04-21 09:10:262622browse

In projects with separate front-end and back-end, the login function is an essential function. The front end needs to write some JavaScript code to implement the login function. Let’s talk about how to use JavaScript to implement the login function.

First of all, we need to understand cookie and session in the HTTP protocol, both of which are important concepts for realizing the login function. When the user submits a login request, the server will verify whether the account and password submitted by the user are correct. If correct, the user information will be saved in the session, and the session id will be saved in the client's cookie in the response header so that the server can request it next time. User information can be found by session id. After successful login, the client can determine whether the user is logged in based on the session id in the cookie, thereby maintaining state.

With this basic knowledge, we can start to implement the login function.

  1. Create a login form

First, we need to create a login form in HTML. The form contains two input boxes for account number and password, and a login button.

<form id="login-form">
  <label for="username">账号:</label>
  <input type="text" id="username" name="username">
  <br>
  <label for="password">密码:</label>
  <input type="password" id="password" name="password">
  <br>
  <button type="submit">登录</button>
</form>

In the form, we assign an id to each input box to facilitate JavaScript to obtain the value in the input box.

  1. Listen to the form submission event

We need to listen to the form submission event and process the login logic in the submission event.

const form = document.querySelector('#login-form');
form.addEventListener('submit', handleLogin);

function handleLogin(event) {
  event.preventDefault(); // 阻止表单默认提交事件
  const username = document.querySelector('#username').value;
  const password = document.querySelector('#password').value;
  // TODO: 验证账号密码是否正确
  // TODO: 发送登录请求
}

First get the value of the account and password input box in the form through the document.querySelector method. Then you can verify the account password. You can write the verification logic yourself or use a third party. library for verification.

  1. Send login request

If the account password verification is passed, you can send a login request. To send a request, you need to use the XMLHttpRequest object, and the fetch API will be used in the following examples.

const form = document.querySelector('#login-form');
form.addEventListener('submit', handleLogin);

function handleLogin(event) {
  event.preventDefault(); // 阻止表单默认提交事件
  const username = document.querySelector('#username').value;
  const password = document.querySelector('#password').value;
  // TODO: 验证账号密码是否正确
  fetch('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password })
  })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('登录成功');
        // TODO: 保存用户信息到 session
        // TODO: 跳转到首页
      } else {
        alert('登录失败,账号或密码错误');
      }
    })
    .catch(error => {
      console.error(error);
      alert('登录失败,网络异常');
    });
}

When sending a request, you need to encapsulate the account password into a JSON object as the request body, and then specify the Content-Type as application/json in the request header. The data returned by the server is a JSON object, which contains a success field indicating whether the login is successful. If the login is successful, the user information can be saved in the session and jumped to the homepage; if the login fails, an error message will pop up.

  1. Save user information to session

After successful login, the server needs to save user information to session. You can use the fetch API to send another request, and set credentials to include in the request so that the cookie is automatically carried when sending the request, so that the corresponding session can be accessed through the session id in the cookie on the server side.

fetch('/api/user', {
  credentials: 'include'
})
  .then(response => response.json())
  .then(data => {
    // TODO: 将用户信息保存到 session
  })
  .catch(error => {
    console.error(error);
    alert('获取用户信息失败');
  });

On the server side, you can use express-session middleware to handle sessions. After successful login, save the user information to the session:

app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  // TODO: 验证账号密码是否正确
  // TODO: 将用户信息保存到 session
  req.session.user = { id: 1, username: 'admin' };
  res.json({ success: true });
});

When obtaining user information, you can obtain the logged in user information through req.session.user:

app.get('/api/user', (req, res) => {
  res.json(req.session.user);
});
  1. Page jump

After successfully logging in, you need to jump to the home page. You can use JavaScript to jump to the page.

if (data.success) {
  alert('登录成功');
  // TODO: 保存用户信息到 session
  window.location.href = '/'; // 跳转到首页
} else {
  alert('登录失败,账号或密码错误');
}

When jumping to a page, you can use the window.location.href property to set the URL of the page to achieve page jumping.

Summary:

This article introduces how to use JavaScript to implement the login function. Implementing login requires processing many aspects, including verifying account and password, sending requests, saving user information to session, page jumps, etc. Through the introduction of this article, I believe readers can quickly master the method of implementing the login function on the front end.

The above is the detailed content of How to use JavaScript to implement login functionality. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn