web前段开发 登录界面输入账号密码后跳转到对应页面的相关代码
时间: 2023-12-06 08:05:34 浏览: 44
这个问题的答案涉及到具体的技术栈和实现方式,下面提供一种常见的实现方式:
前端代码:
```html
<form id="loginForm">
<input type="text" name="username" placeholder="请输入用户名">
<input type="password" name="password" placeholder="请输入密码">
<button type="submit">登录</button>
</form>
```
```javascript
document.getElementById('loginForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单提交的默认行为
var form = event.target;
var formData = new FormData(form); // 获取表单数据
fetch('/api/login', { // 向后端发送登录请求
method: 'POST',
body: formData
}).then(function(response) {
if (response.ok) {
window.location.href = '/dashboard'; // 登录成功后跳转到对应页面
} else {
alert('登录失败,请检查用户名和密码是否正确');
}
}).catch(function(error) {
console.error(error);
});
});
```
后端代码(使用Express框架):
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/login', function(req, res) {
const username = req.body.username;
const password = req.body.password;
if (username === 'admin' && password === '123456') {
res.sendStatus(200); // 登录成功,返回200状态码
} else {
res.sendStatus(401); // 登录失败,返回401状态码
}
});
app.listen(3000, function() {
console.log('Server is running on http://localhost:3000');
});
```
注意:上述代码仅作为示例,实际情况中还需要进行安全性和错误处理等方面的考虑。