用户名密码 简单的登录验证 可以不使用框架 前端登录 js 绑定 login() 以及后端代码
时间: 2024-02-25 20:52:59 浏览: 16
好的,如果你想实现一个简单的用户名密码登录验证,可以按照以下步骤进行:
前端代码:
1. 在 HTML 文件中创建一个表单,包括用户名和密码的输入框,以及一个提交按钮:
```html
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="button" value="Login" onclick="login()">
</form>
```
2. 创建一个 JavaScript 函数 `login()`,在函数内部获取到用户名和密码的值,并通过 AJAX 发送 POST 请求到后端:
```javascript
function login() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "/login");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {
if (xhr.status === 200) {
alert("Login success!");
} else {
alert("Login failed!");
}
};
xhr.send(JSON.stringify({username: username, password: password}));
}
```
后端代码:
1. 使用 Node.js 创建一个简单的 HTTP 服务器,监听一个端口:
```javascript
const http = require("http");
const server = http.createServer((req, res) => {
// handle requests here
});
server.listen(8080);
```
2. 在服务器中处理 POST 请求,获取到用户名和密码的值,进行验证:
```javascript
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/login") {
let body = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", () => {
const {username, password} = JSON.parse(body);
if (verifyUser(username, password)) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Login success!");
} else {
res.writeHead(401, {"Content-Type": "text/plain"});
res.end("Login failed!");
}
});
} else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("Not found");
}
});
server.listen(8080);
function verifyUser(username, password) {
// verify user here, return true if username and password are correct, false otherwise
}
```
以上是一个简单的用户名密码登录验证的实现,仅作参考。具体的实现方式可以根据需求进行调整。