JavaScript is a commonly used programming language, usually used for interactive effects and dynamic data processing on Web pages. In web applications, login is a very important function, which involves issues such as the security and privacy protection of user information. Today we will explore how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users and logging out, etc.
Verify user input
Before setting up the login function, we need to ensure that the information entered by the user is legal and valid, such as user name and password. To validate user input, we can use methods such as regular expressions, form validation, and server-side authentication.
Regular expression is a language for matching patterns, which can help us check whether the input is valid or well-formatted. For example, a simple regular expression can check whether the input is a valid email address:
function validateEmail(email) { const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); }
Form validation is another method of validating user input. It can check the input by setting rules and error prompts. effectiveness. For example, we can use HTML and JavaScript code to validate a login form, ensuring that both the username and password are required and that the username contains at least 6 characters:
<form id="loginForm" onsubmit="return validateForm()"> <label for="username">Username:</label> <input type="text" id="username" name="username" required minlength="6"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br><br> <input type="submit" value="Log in"> </form> <script> function validateForm() { const username = document.getElementById("username").value; const password = document.getElementById("password").value; if (username.length < 6) { document.getElementById("username").setCustomValidity("Username must contain at least 6 characters"); return false; } else { document.getElementById("username").setCustomValidity(""); } if (password.length < 8) { document.getElementById("password").setCustomValidity("Password must contain at least 8 characters"); return false; } else { document.getElementById("password").setCustomValidity(""); } return true; } </script>
Server-side authentication is the last line of defense. It ensures that the information entered by the user is legal and valid as it verifies that the username and password match the records in the database. For example, we can use Node.js and the Express framework to implement server-side authentication:
app.post('/login', function(req, res) { const username = req.body.username; const password = req.body.password; if(username === 'admin' && password === 'admin') { res.status(200).send('Login successful'); } else { res.status(401).send('Invalid username or password'); } });
Handling login requests
Once the user has entered a valid username and password, and the verification has passed, we need Use it to handle login requests and create sessions. A session is an interaction method between the server and the client, which allows the server to maintain contact with the client for a certain period of time and save the user's status and information on the server.
In web applications, we can use cookies and sessions to create and manage user sessions. Among them, a cookie is a small text file that can be stored in the user's computer by the web browser and sent to the server the next time it visits the website; the session is a server-side data structure that can store and manage user status and information.
For example, we can use JavaScript code to create a session and store user information:
function login(username, password) { const xhr = new XMLHttpRequest(); xhr.open('POST', '/login'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); const user = response.user; const sessionId = response.sessionId; // Save user information and sessionId in cookies document.cookie = `user=${user}`; document.cookie = `sessionId=${sessionId}`; // Redirect user to home page window.location.href = '/home'; } else { alert('Invalid username or password'); } }; const data = JSON.stringify({ username: username, password: password }); xhr.send(data); }
In this example, we use the XMLHttpRequest object to send a POST request, sending the username and password to the server authenticating. If the login is successful, the server will return the user information and session ID, which we can store in cookies. We then redirect the user to the home page, maintaining the user session through the information in the cookie.
Remember User
After the user logs in, we can improve the user experience by remembering the username and password, and allow the user to log in automatically the next time they visit the website. This can be achieved by storing username and password in cookies.
For example, we can use JavaScript code to remember a user's username and password:
function rememberMe() { const username = document.getElementById('username').value; const password = document.getElementById('password').value; if (document.getElementById('rememberMe').checked) { // Save username and password in cookies for 30 days const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString(); document.cookie = `username=${username}; expires=${expires};`; document.cookie = `password=${password}; expires=${expires};`; } else { // Remove username and password from cookies document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"; document.cookie = "password=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"; } }
In this example, we use a checkbox to represent the "Remember Me" option. If the user checks this option, we store the username and password in a cookie and set the expiration time to 30 days. If the user cancels this option, we will delete the username and password from the cookie.
Log out
Finally, we need to provide a convenient way for users to log out to avoid accidental or illegal use of the user's account. Logging out requires destroying the user session and clearing the information in cookies.
For example, we can use JavaScript code to log out:
function logout() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/logout'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { // Remove user information and sessionId from cookies document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'; document.cookie = 'sessionId=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'; // Redirect user to login page window.location.href = '/login'; } else { alert('Logout failed'); } }; const sessionId = getCookie('sessionId'); const data = JSON.stringify({ sessionId: sessionId }); xhr.send(data); }
In this example, we use the XMLHttpRequest object to send a POST request and send the session ID to the server. The server will destroy the user session and return a success status code. We will then remove the user information and session ID from the cookie and redirect the user to the login page.
Conclusion
In this article, we explored how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users, and logging out. Login is a very important function in web applications, which involves important issues such as the security and privacy protection of user information. By using technologies such as JavaScript and server-side authentication, we can ensure that the information entered by users is legal and valid, and improve user experience and security.
The above is the detailed content of JavaScript settings login. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

Immutable updates are crucial in React because it ensures that state changes can be detected correctly, triggering component re-rendering and avoiding side effects. Directly modifying state, such as push or assignment, will cause React to be unable to detect changes. The correct way to do this is to create new objects instead of old objects, such as updating an array or object using the expand operator. For nested structures, you need to copy layer by layer and modify only the target part, such as using multiple expansion operators to deal with deep attributes. Common operations include updating array elements with maps, deleting elements with filters, adding elements with slices or expansion. Tool libraries such as Immer can simplify the process, allowing "seemingly" to modify the original state but generate new copies, but increase project complexity. Key tips include each

Front-end applications should set security headers to improve security, including: 1. Configure basic security headers such as CSP to prevent XSS, X-Content-Type-Options to prevent MIME guessing, X-Frame-Options to prevent click hijacking, X-XSS-Protection to disable old filters, HSTS to force HTTPS; 2. CSP settings should avoid using unsafe-inline and unsafe-eval, use nonce or hash and enable reporting mode testing; 3. HTTPS-related headers include HSTS automatic upgrade request and Referrer-Policy to control Referer; 4. Other recommended headers such as Permis

The data-* attribute is used in HTML to store additional data, and its advantages include that the data is closely related to elements and comply with HTML5 standards. 1. When using it, name it starts with data-, such as data-product-id; 2. It can be accessed through JavaScript's getAttribute or dataset; 3. Best practices include avoiding sensitive information, reasonable naming, paying attention to performance and not replacing state management.

To style SVGs using CSS, you first need to embed SVGs inline into HTML for fine control. 1. Inline SVG allows its internal elements such as or to be directly selected through CSS and to apply styles, while external SVG only supports global styles such as width and height or filters. 2. Use regular CSS syntax such as .class:hover to achieve interactive effects, but use fill instead of color to control the color, and use stroke and stroke-width to control the outline. 3. Use class names to organize styles to avoid duplication and pay attention to naming conflicts and scope management. 4. The SVG style may be inherited from the page, and can be reset through svg*{fill:none;stroke:none;} to avoid

Adding website Favicon requires preparing icon files, placing the correct path and quoting them. 1. Prepare multi-size .ico or .png icons, which can be generated by online tools; 2. Put favicon.ico in the website root directory; 3. If you need to customize the path or support more devices, you need to add a link tag reference in the HTMLhead; 4. Clear the cache or use the tool to check whether it is effective.
