用node.js一个登录界面,数据增删改查的接口
时间: 2024-02-19 11:57:51 浏览: 19
好的,以下是使用 Node.js 实现登录界面和数据增删改查的接口的示例代码:
## 登录界面
### HTML 部分
```html
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="/login" method="POST">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<br>
<button type="submit">登录</button>
</form>
</body>
</html>
```
### Node.js 部分
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/login.html');
});
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
// 在此处验证用户名和密码是否正确,并进行相应的处理
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
```
## 数据增删改查接口
### Node.js 部分
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 模拟一个数据库
const data = [
{ id: 1, name: '张三', age: 18 },
{ id: 2, name: '李四', age: 20 },
{ id: 3, name: '王五', age: 22 },
];
// 获取所有数据
app.get('/data', (req, res) => {
res.json(data);
});
// 获取指定 ID 的数据
app.get('/data/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = data.find(item => item.id === id);
if (item) {
res.json(item);
} else {
res.sendStatus(404);
}
});
// 添加数据
app.post('/data', (req, res) => {
const item = req.body;
if (item.id && item.name && item.age) {
data.push(item);
res.sendStatus(201);
} else {
res.sendStatus(400);
}
});
// 修改数据
app.put('/data/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = req.body;
const index = data.findIndex(item => item.id === id);
if (index !== -1) {
data.splice(index, 1, { id, ...item });
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});
// 删除数据
app.delete('/data/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = data.findIndex(item => item.id === id);
if (index !== -1) {
data.splice(index, 1);
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
```
这样就完成了一个简单的登录界面和数据增删改查的接口。