帮我用 express+sequelize +mysql2分多个模块写一个demo
时间: 2023-12-31 18:05:28 浏览: 129
nodejs + express + mysql demo
4星 · 用户满意度95%
好的,下面是一个使用 Express.js、Sequelize 和 mysql2 实现的简单 demo,将其拆分为多个模块:
1. 安装依赖
```
npm install express sequelize mysql2
```
2. 创建数据库和数据表
```
CREATE DATABASE IF NOT EXISTS demo;
USE demo;
CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
```
3. 创建 Sequelize 模型
在 models/user.js 文件中:
```javascript
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
module.exports = User;
```
4. 创建 Express.js 应用
在 app.js 文件中:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/users', userRoutes);
app.listen(3000, () => console.log('Server running on port 3000'));
```
5. 创建 Sequelize 数据库连接
在 config/database.js 文件中:
```javascript
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('demo', 'root', 'password', {
host: 'localhost',
dialect: 'mysql',
});
module.exports = sequelize;
```
6. 创建用户路由
在 routes/userRoutes.js 文件中:
```javascript
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/UserController');
router.get('/', UserController.getAllUsers);
router.get('/:id', UserController.getUserById);
router.post('/', UserController.createUser);
router.put('/:id', UserController.updateUser);
router.delete('/:id', UserController.deleteUser);
module.exports = router;
```
7. 创建用户控制器
在 controllers/UserController.js 文件中:
```javascript
const User = require('../models/User');
exports.getAllUsers = async (req, res) => {
const users = await User.findAll();
res.json(users);
};
exports.getUserById = async (req, res) => {
const user = await User.findByPk(req.params.id);
res.json(user);
};
exports.createUser = async (req, res) => {
const { name, email, password } = req.body;
const user = await User.create({ name, email, password });
res.json(user);
};
exports.updateUser = async (req, res) => {
const { name, email, password } = req.body;
await User.update({ name, email, password }, { where: { id: req.params.id } });
res.json({ message: 'User updated successfully.' });
};
exports.deleteUser = async (req, res) => {
await User.destroy({ where: { id: req.params.id } });
res.json({ message: 'User deleted successfully.' });
};
```
现在,我们已经将应用拆分为多个模块,可以通过运行 `node app.js` 启动应用。然后可以使用 Postman 或其他工具测试 API。
阅读全文