最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Node.js 數(shù)據(jù)庫(kù) CRUD 項(xiàng)目示例詳解(完美解決方案)

 更新時(shí)間:2025年04月16日 10:00:19   作者:veminhe  
這篇文章主要介紹了Node.js 數(shù)據(jù)庫(kù) CRUD 項(xiàng)目示例詳解(完美解決方案),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧

希望使用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)文章

  • 基于node.js express mvc輕量級(jí)框架實(shí)踐

    基于node.js express mvc輕量級(jí)框架實(shí)踐

    下面小編就為大家?guī)?lái)一篇基于node.js express mvc輕量級(jí)框架實(shí)踐。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • package.json中overrides用法示例詳解

    package.json中overrides用法示例詳解

    在前端開(kāi)發(fā)中,package.json和package-lock.json是兩個(gè)經(jīng)常打交道的文件,這篇文章主要介紹了package.json中overrides用法的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2026-02-02
  • 如何降低node版本,怎樣實(shí)現(xiàn)降低node版本

    如何降低node版本,怎樣實(shí)現(xiàn)降低node版本

    這篇文章主要介紹了如何降低node版本,怎樣降低node版本問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • json對(duì)象及數(shù)組鍵值的深度大小寫(xiě)轉(zhuǎn)換問(wèn)題詳解

    json對(duì)象及數(shù)組鍵值的深度大小寫(xiě)轉(zhuǎn)換問(wèn)題詳解

    這篇文章主要給大家介紹了關(guān)于json對(duì)象及數(shù)組鍵值的深度大小寫(xiě)轉(zhuǎn)換問(wèn)題的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-03-03
  • Node卸載超詳細(xì)步驟(附圖文講解!)

    Node卸載超詳細(xì)步驟(附圖文講解!)

    由于之前的node為8.0版本,不太滿足需求,所以需要安裝高版本的node,下面這篇文章主要給大家介紹了關(guān)于Node卸載超詳細(xì)步驟的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • node獲取命令行中的參數(shù)詳解

    node獲取命令行中的參數(shù)詳解

    這篇文章主要為大家介紹了node獲取命令行中的參數(shù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • nodejs 使用http進(jìn)行post或get請(qǐng)求的實(shí)例(攜帶cookie)

    nodejs 使用http進(jìn)行post或get請(qǐng)求的實(shí)例(攜帶cookie)

    今天小編就為大家分享一篇nodejs 使用http進(jìn)行post或get請(qǐng)求的實(shí)例(攜帶cookie),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • 教你用十行node.js代碼讀取docx的文本

    教你用十行node.js代碼讀取docx的文本

    這篇文章主要給大家介紹了用十行node.js代碼讀取docx文本的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-03-03
  • 詳解NodeJS Https HSM雙向認(rèn)證實(shí)現(xiàn)

    詳解NodeJS Https HSM雙向認(rèn)證實(shí)現(xiàn)

    這篇文章主要介紹了詳解NodeJS Https HSM雙向認(rèn)證實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-03-03
  • Node.js進(jìn)程管理之Process模塊詳解

    Node.js進(jìn)程管理之Process模塊詳解

    本文詳細(xì)講解了Node.js進(jìn)程管理之Process模塊,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07

最新評(píng)論

赣榆县| 勐海县| 沁阳市| 甘洛县| 霸州市| 固镇县| 日喀则市| 南充市| 班玛县| 城步| 阿拉善左旗| 得荣县| 珠海市| 定陶县| 石台县| 开原市| 漠河县| 和政县| 东乡族自治县| 临泉县| 斗六市| 新沂市| 阿拉善盟| 长汀县| 历史| 呈贡县| 登封市| 唐海县| 思南县| 黄浦区| 尼木县| 兴化市| 开阳县| 静安区| 商水县| 博客| 沂南县| 南京市| 封丘县| 边坝县| 静海县|