1. 数据库搭建
选择MySQL数据库,创建用户表:
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
2. 后端实现
使用Express框架,搭建基本的API接口:
```javascript
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'flipkart'
});
db.connect(err => {
if (err) throw err;
console.log('Database connected!');
});
// 创建新用户
app.post('/api/users', (req, res) => {
const { username, password, email } = req.body;
const sql = 'INSERT INTO users (username, password, email) VALUES (?, ?, ?)';
db.query(sql, [username, password, email], (err, result) => {
if (err) throw err;
res.send('User created successfully!');
});
});
// 修改用户信息
app.put('/api/users/:id', (req, res) => {
const { id } = req.params;
const { username, password, email } = req.body;
const sql = 'UPDATE users SET username = ?, password = ?, email = ? WHERE id = ?';
db.query(sql, [username, password, email, id], (err, result) => {
if (err) throw err;
res.send('User updated successfully!');
});
});
// 删除用户
app.delete('/api/users/:id', (req, res) => {
const { id } = req.params;
const sql = 'DELETE FROM users WHERE id = ?';
db.query(sql, [id], (err, result) => {
if (err) throw err;
res.send('User deleted successfully!');
});
});
// 查询用户
app.get('/api/users/:id', (req, res) => {
const { id } = req.params;
const sql = 'SELECT * FROM users WHERE id = ?';
db.query(sql, [id], (err, result) => {
if (err) throw err;
res.json(result);
});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
三、系统维护
1. 数据备份
定期备份数据库,以防止数据丢失。可以使用MySQL的定时任务来实现:
```sql
CREATE EVENT backup_event
ON SCHEDULE EVERY 1 DAY
DO
BACKUP DATABASE flipkart TO DISK = 'C:/backup/flipkart.bak';
```
2. 系统监控
监控系统的运行状态,及时发现并处理异常情况。可以使用一些开源的监控工具,如Prometheus和Grafana。
3. 安全防护
确保系统的安全性,防止SQL注入、XSS攻击等。可以使用一些安全中间件,如helmet和express-validator。