实现用户登陆功能(需要写出前端和服务器端的核心代码)。提示:假设用户名和密码分别为“admin”和“admin123”则认为登陆成功,否则登陆失败,并在页面显示错误提示信息)。
时间: 2024-10-22 18:30:23 浏览: 17
为了实现用户登录功能,我们通常会在前端使用JavaScript处理用户输入并发送请求到服务器,然后在服务器端验证这些凭据。以下是简单的前端和后端核心代码示例:
**前端(HTML + JavaScript - 使用fetch API)**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form id="loginForm">
<input type="text" id="username" placeholder="Username" required>
<input type="password" id="password" placeholder="Password" required>
<button type="submit">Login</button>
<div id="error"></div>
</form>
<script>
document.getElementById('loginForm').addEventListener('submit', async (event) => {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
// 登陆成功后跳转到其他页面或者隐藏错误信息
alert("Login successful");
} else {
const error = await response.json();
document.getElementById('error').innerText = error.message;
}
} catch (error) {
console.error(error);
document.getElementById('error').innerText = "Error occurred while logging in";
}
});
</script>
</body>
</html>
```
**后端(Node.js + Express)**:
```javascript
const express = require('express');
const app = express();
app.use(express.json());
// 假设有一个数据库连接和验证函数在这里
const validateCredentials = async (username, password) => {
// 检查`admin`和`admin123`
return (username === 'admin' && password === 'admin123') ? { message: 'Login successful' } : { message: 'Invalid credentials' };
};
// 用户登录路由
app.post('/api/login', async (req, res) => {
try {
const { username, password } = req.body;
const result = await validateCredentials(username, password);
res.status(200).json(result);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
```
**
阅读全文