JavaScript 实现登录注册功能涉及前端和后端的交互。以下是一个基本的实现思路,包括前端和后端的代码示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login and Register</title>
</head>
<body>
<h2>Login</h2>
<form id="loginForm">
<input type="text" id="loginUsername" placeholder="Username" required>
<input type="password" id="loginPassword" placeholder="Password" required>
<button type="submit">Login</button>
</form>
<h2>Register</h2>
<form id="registerForm">
<input type="text" id="registerUsername" placeholder="Username" required>
<input type="password" id="registerPassword" placeholder="Password" required>
<button type="submit">Register</button>
</form>
<script>
document.getElementById('loginForm').addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Login successful!');
} else {
alert('Login failed: ' + data.message);
}
});
});
document.getElementById('registerForm').addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('registerUsername').value;
const password = document.getElementById('registerPassword').value;
fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Registration successful!');
} else {
alert('Registration failed: ' + data.message);
}
});
});
</script>
</body>
</html>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let users = {}; // 模拟用户数据库
app.post('/api/register', (req, res) => {
const { username, password } = req.body;
if (users[username]) {
return res.json({ success: false, message: 'Username already exists' });
}
users[username] = password;
res.json({ success: true, message: 'Registration successful' });
});
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (users[username] === password) {
return res.json({ success: true, message: 'Login successful' });
}
res.json({ success: false, message: 'Invalid username or password' });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});通过以上步骤,你可以实现一个基本的登录注册功能,并解决一些常见问题。
没有搜到相关的文章