Node.js 數(shù)據(jù)庫(kù) CRUD 項(xiàng)目示例詳解(完美解決方案)
希望使用Nodejs操作數(shù)據(jù)庫(kù)做CRUD,用deepseek實(shí)戰(zhàn)搜索“使用Nodejs對(duì)數(shù)據(jù)庫(kù)表做CRUD的項(xiàng)目例子”,找到了解決方案,如下圖所示:

項(xiàng)目結(jié)構(gòu)
nodejs-crud-example/ ├── config/ │ └── db.js # 數(shù)據(jù)庫(kù)連接配置 ├── controllers/ │ └── userController.js # 業(yè)務(wù)邏輯 ├── models/ │ └── userModel.js # 數(shù)據(jù)庫(kù)操作 ├── routes/ │ └── userRoutes.js # 路由定義 ├── app.js # 應(yīng)用入口 ├── package.json └── README.md
1. 初始化項(xiàng)目
mkdir nodejs-crud-example cd nodejs-crud-example npm init -y npm install express mysql2 body-parser cors

2. 配置數(shù)據(jù)庫(kù)連接 (config/db.js)
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'testdb',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;3. 創(chuàng)建模型 (models/userModel.js)
const pool = require('../config/db');
class User {
static async getAll() {
const [rows] = await pool.query('SELECT * FROM users');
return rows;
}
static async getById(id) {
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
return rows[0];
}
static async create(name, email) {
const [result] = await pool.query(
'INSERT INTO users (name, email) VALUES (?, ?)',
[name, email]
);
return { id: result.insertId, name, email };
}
static async update(id, name, email) {
await pool.query(
'UPDATE users SET name = ?, email = ? WHERE id = ?',
[name, email, id]
);
return { id, name, email };
}
static async delete(id) {
await pool.query('DELETE FROM users WHERE id = ?', [id]);
return true;
}
}
module.exports = User;4. 創(chuàng)建控制器 (controllers/userController.js)
const User = require('../models/userModel');
exports.getAllUsers = async (req, res) => {
try {
const users = await User.getAll();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
exports.getUser = async (req, res) => {
try {
const user = await User.getById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
exports.createUser = async (req, res) => {
try {
const { name, email } = req.body;
const newUser = await User.create(name, email);
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.updateUser = async (req, res) => {
try {
const { name, email } = req.body;
const updatedUser = await User.update(req.params.id, name, email);
res.json(updatedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.deleteUser = async (req, res) => {
try {
await User.delete(req.params.id);
res.json({ message: 'User deleted successfully' });
} catch (err) {
res.status(500).json({ message: err.message });
}
};5. 創(chuàng)建路由 (routes/userRoutes.js)
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
// CRUD 路由
router.get('/', userController.getAllUsers);
router.get('/:id', userController.getUser);
router.post('/', userController.createUser);
router.put('/:id', userController.updateUser);
router.delete('/:id', userController.deleteUser);
module.exports = router;6. 應(yīng)用入口 (app.js)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const userRoutes = require('./routes/userRoutes');
const app = express();
// 中間件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 路由
app.use('/api/users', userRoutes);
// 錯(cuò)誤處理
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something broke!' });
});
// 啟動(dòng)服務(wù)器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});7. 創(chuàng)建數(shù)據(jù)庫(kù)表
在 MySQL 中執(zhí)行以下 SQL 創(chuàng)建 users 表:
CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
8. 測(cè)試 API
你可以使用 Postman 或 curl 測(cè)試這些端點(diǎn):
- 獲取所有用戶:
GET /api/users - 訪問(wèn)http://localhost:3000/api/users
- 結(jié)果為:

獲取單個(gè)用戶: GET /api/users/1
訪問(wèn)http://localhost:3000/api/users/1

創(chuàng)建用戶:
在cmd窗口中執(zhí)行

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' http://localhost:3000/api/users
更新用戶:
在cmd窗口中執(zhí)行

curl -X PUT -H "Content-Type: application/json" -d '{"name":"John Updated","email":"john.new@example.com"}' http://localhost:3000/api/users/1
刪除用戶: DELETE /api/users/1
在cmd窗口中執(zhí)行

curl -X DELETE -H "Content-Type: application/json" http://localhost:3000/api/users/1
到此這篇關(guān)于Node.js 數(shù)據(jù)庫(kù) CRUD 項(xiàng)目示例的文章就介紹到這了,更多相關(guān)Node.js 數(shù)據(jù)庫(kù) CRUD內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
koa2實(shí)現(xiàn)登錄注冊(cè)功能的示例代碼
這篇文章主要介紹了koa2實(shí)現(xiàn)登錄注冊(cè)功能的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
windows使用nvm對(duì)node進(jìn)行版本管理切換的完整步驟
這篇文章主要介紹了windows使用nvm對(duì)node進(jìn)行版本管理切換的完整步驟,在使用之前各位務(wù)必卸載掉自己安裝過(guò)的nvm或者node版本包括環(huán)境變量之類(lèi)的,要保證自己的電腦完全沒(méi)有node環(huán)境,需要的朋友可以參考下2024-03-03
Node.js中path.join()優(yōu)勢(shì)例舉分析
在本篇文章里小編給大家整理的是一篇關(guān)于Node.js中path.join()優(yōu)勢(shì)例舉分析,有興趣的朋友們可以學(xué)習(xí)下。2021-08-08
詳解nodejs的express如何自動(dòng)生成項(xiàng)目框架
本篇文章主要介紹了nodejs的express如何自動(dòng)生成項(xiàng)目框架,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
node.js使用Moment.js js 時(shí)間計(jì)算方法示例小結(jié)
這篇文章主要介紹了node.js使用Moment.js js 時(shí)間計(jì)算方法,結(jié)合實(shí)例形式分析了Moment.js js模塊時(shí)間計(jì)算的常用操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2023-05-05
基于node.js實(shí)現(xiàn)微信支付退款功能
在微信開(kāi)發(fā)中有有付款就會(huì)有退款,這樣的功能非常常見(jiàn),這篇文章主要介紹了node.js實(shí)現(xiàn)微信支付退款功能,需要的朋友可以參考下2017-12-12
Node.js API詳解之 dns模塊用法實(shí)例分析
這篇文章主要介紹了Node.js API詳解之 dns模塊用法,結(jié)合實(shí)例形式分析了Node.js API中dns模塊基本功能、相關(guān)函數(shù)與使用技巧,需要的朋友可以參考下2020-05-05

