如何用jQuery获取Node.js登录API的Token并存入LocalStorage?
Solution: Capture Login Token with jQuery and Store in localStorage
Great question! Since you already have the registration flow working with jQuery, extending this to handle login and token storage is straightforward. Here's how to implement it step by step:
Step 1: Set Up Your Login Form Elements
First, make sure you have the necessary HTML elements for the login form (adjust IDs to match your actual markup):
<input type="email" id="login-email" placeholder="Your Email"> <input type="password" id="login-password" placeholder="Your Password"> <button id="login-button">Login</button>
Step 2: jQuery Login Handler with Token Capture
Add this jQuery code to handle the login click event, send the request to your API, and store the token in localStorage:
$('#login-button').click(function(e) { // Prevent default form submission behavior (if using a <form> tag) e.preventDefault(); // Collect login credentials from input fields const loginPayload = { email: $("#login-email").val(), password: $("#login-password").val() }; $.ajax({ type: "POST", url: "http://localhost:3001/api/users/login", data: JSON.stringify(loginPayload), contentType: "application/json; charset=utf-8", dataType: "text", // Critical: Your backend sends the token as plain text success: function(token, _, jqXHR) { // Option 1: Use the token directly from the response body localStorage.setItem('auth-token', token); // Option 2: Alternatively, fetch it from the 'auth-token' response header // const tokenFromHeader = jqXHR.getResponseHeader('auth-token'); // localStorage.setItem('auth-token', tokenFromHeader); console.log("Login successful! Token saved to localStorage."); // Redirect to your app's dashboard or protected page here // window.location.href = "/dashboard"; }, error: function(jqXHR) { // Display the error message returned by your backend alert(jqXHR.responseText); console.error("Login failed:", jqXHR.responseText); } }); });
Key Details Explained:
dataType: "text": Your backend sends the token as a raw string (not JSON), so setting this ensures jQuery doesn’t attempt to parse it as JSON (which would cause an error).- Token Storage:
localStorage.setItem('auth-token', token)persists the token across browser sessions, making it available for future authenticated requests. - Error Handling: The
errorcallback captures 400 status responses from your backend and displays the meaningful error messages you’ve defined (like "Email or password don't match").
Using the Token for Authenticated Requests
When making requests to protected API endpoints later, retrieve the token from localStorage and include it in the request headers:
$.ajax({ url: "http://localhost:3001/api/protected-endpoint", headers: { "auth-token": localStorage.getItem('auth-token') }, // ... rest of your request configuration });
Logout (Clearing the Token)
To log the user out, simply remove the token from localStorage:
localStorage.removeItem('auth-token'); // Redirect to login page window.location.href = "/login";
内容的提问来源于stack exchange,提问作者Vitor Ramalho
相关产品推荐
相关产品推荐

