前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form>
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br><br>
        <button type="button" onclick="login()">Login</button>
    </form>
    <script>
        function login() {
            const username = document.getElementById("username").value;
            const password = document.getElementById("password").value;
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "/login", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        alert("Login successful!");
                    } else {
                        alert("Login failed!");
                    }
                }
            };
            const data = JSON.stringify({ username: username, password: password });
            xhr.send(data);
        }
    </script>
</body>
</html>

后端代码(使用 Express 框架):

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

app.post("/login", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    // 在此处进行用户名和密码的验证,验证成功返回 200,否则返回 401
    if (username === "admin" && password === "admin") {
        res.sendStatus(200);
    } else {
        res.sendStatus(401);
    }
});

app.listen(8080, () => {
    console.log("Server started on port 8080.");
});
``
实现前端通过Button按钮实现表单提交用户名和密码到后端完成登陆验证的完整代码

原文地址: http://www.cveoy.top/t/topic/dXhY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录