当前位置: 首页 > news >正文

Sequelize+Sqlite3使用示例

        以下是一个简单的示例,展示了如何在Node.js中使用Express框架、Sequelize ORM以及SQLite数据库来构建一个支持RESTful API的Web应用程序。

一,安装必要的npm包:

npm install express sequelize sqlite3 body-parser

二,创建JavaScript文件

(例如app.js),并添加以下代码:

const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');
const bodyParser = require('body-parser');// 初始化Express应用
const app = express();
app.use(bodyParser.json());// 配置Sequelize以使用SQLite数据库
const sequelize = new Sequelize({dialect: 'sqlite',storage: 'database.sqlite' // SQLite数据库文件的路径
});// 定义User模型
const User = sequelize.define('User', {username: {type: DataTypes.STRING,allowNull: false,unique: true // 用户名唯一},email: {type: DataTypes.STRING,allowNull: false,unique: true // 邮箱唯一}
});// 同步模型到数据库(创建表)
sequelize.sync().then(() => {console.log('Database & tables created!');// 定义RESTful路由// 获取所有用户app.get('/users', async (req, res) => {try {const users = await User.findAll();res.json(users);} catch (error) {res.status(500).json({ error: error.message });}});// 根据ID获取用户app.get('/users/:id', async (req, res) => {try {const user = await User.findByPk(req.params.id);if (!user) {return res.status(404).json({ error: 'User not found' });}res.json(user);} catch (error) {res.status(500).json({ error: error.message });}});// 创建新用户app.post('/users', async (req, res) => {try {const user = await User.create(req.body);res.status(201).json(user);} catch (error) {res.status(400).json({ error: error.message });}});// 更新用户app.put('/users/:id', async (req, res) => {try {const user = await User.findByPk(req.params.id);if (!user) {return res.status(404).json({ error: 'User not found' });}await user.update(req.body);res.json(user);} catch (error) {res.status(500).json({ error: error.message });}});// 删除用户app.delete('/users/:id', async (req, res) => {try {const user = await User.findByPk(req.params.id);if (!user) {return res.status(404).json({ error: 'User not found' });}await user.destroy();res.json({ message: 'User deleted' });} catch (error) {res.status(500).json({ error: error.message });}});// 启动Express服务器const PORT = process.env.PORT || 3000;app.listen(PORT, () => {console.log(`Server is running on port ${PORT}`);});}).catch(error => {console.error('Unable to connect to the database:', error);
});

在以上代码中:

  1. 初始化了Express应用,并配置了body-parser中间件来解析JSON请求体。
  2. 配置了Sequelize以使用SQLite数据库,并定义了一个User模型。
  3. 使用sequelize.sync()方法同步模型到数据库(如果数据库和表不存在,它们将被创建)。
  4. 定义了RESTful路由来处理对/users端点的GET、POST、PUT和DELETE请求。
  5. 启动了Express服务器,监听指定的端口。

        运行这个Node.js应用程序,并使用Postman或类似的工具来测试这些RESTful API端点。例如,你可以发送POST请求到/users端点来创建一个新用户,然后发送GET请求到/users端点来获取所有用户。

http://www.lryc.cn/news/482863.html

相关文章:

  • MyBatisPlus 用法详解
  • 强化学习入门笔记(Reinforcement Learning,RL) 强推!
  • C++ QT 工具日志异步分批保存
  • win32com库基于wps对Word文档的基础操作
  • Kubernetes 网络之深度探索:网络模型与 CNI 插件
  • Go 模块管理教程:go.mod 与依赖版本控制
  • 大数据 ETL + Flume 数据清洗 — 详细教程及实例(附常见问题及解决方案)
  • 鸿蒙next版开发:订阅应用事件(ArkTS)
  • F litter 开发之flutter_local_notifications
  • springboot参数校验
  • Spring生态学习路径与源码深度探讨
  • C++:set详解
  • (一)- DRM架构
  • Docker了解
  • 【DL】YOLO11 OBB目标检测 | 模型训练 | 推理
  • vue读取本地excel文件并渲染到列表页面
  • github 以及 huggingface下载模型和数据
  • 使用 Vue 配合豆包MarsCode 实现“小恐龙酷跑“小游戏
  • 51c视觉~合集6
  • STM32(hal库)在串口中,USART和uart有什么区别?
  • 机器学习、深度学习面试知识点汇总
  • FPGA高速设计之Aurora64B/66B的应用与不足的修正
  • 如何通过PHP脚本自动推送WordPress文章至百度站长平台
  • ORA-01092 ORA-14695 ORA-38301
  • upload-labs通关练习---更新到15关
  • WPF 应用程序中使用 Prism 框架时,有多种方式可以注册服务和依赖项
  • 【ESP32】ESP-IDF开发 | 低功耗管理+RTC唤醒和按键唤醒例程
  • Windows 局域网IP扫描工具:IPScaner 轻量免安装
  • HTML的浮动与定位
  • 【网络安全 | 漏洞挖掘】我如何通过路径遍历实现账户接管