写一个登录页面前后端交互
时间: 2023-06-12 12:05:22 浏览: 103
前端页面:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Login</h2>
<form>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
</div>
<button type="button" class="btn btn-primary" onclick="login()">Login</button>
</form>
</div>
<script>
function login() {
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
url: "/login",
type: "POST",
data: {
username: username,
password: password
},
success: function(response) {
alert(response);
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
});
}
</script>
</body>
</html>
```
后端代码(使用 Node.js 和 Express 框架):
```javascript
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/login", function(req, res) {
var username = req.body.username;
var password = req.body.password;
if(username == "admin" && password == "password") {
res.send("Login successful");
} else {
res.status(401).send("Invalid username or password");
}
});
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
```
在这个例子中,当用户在前端页面输入用户名和密码并点击“Login”按钮时,前端页面会通过 AJAX 向后端发送一个 POST 请求,请求地址为 `/login`。后端会获取到 POST 请求中的用户名和密码,如果用户名和密码正确,则返回一个字符串“Login successful”,否则返回一个状态码为 401 的响应,内容为“Invalid username or password”。前端页面在接收到后端的响应后,会弹出一个提示框,显示响应的内容。
阅读全文