首页 > 数据库 >node.js: mysql sequelize in WebStorm 2023.1

node.js: mysql sequelize in WebStorm 2023.1

时间:2024-08-07 18:05:18浏览次数:15  
标签:node const res WebStorm js tutorials message id Tutorial

mysql:

select * from tutorials;
# CREATE TABLE IF NOT EXISTS `tutorials` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
insert into tutorials values(1,'geovindu','geovidu',1,'2025-05-04','2025-05-04');
insert into tutorials values(2,'涂聚文','涂聚文',0,'2025-05-04','2025-05-04');

  

/**
 *  dbConfig.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */

module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "770214",
  DB: "geovindu",
  dialect: "mysql",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};

/*
* http://localhost:8081/api/tutorials
http://localhost:8081/api/tutorials/1
http://localhost:8081/api/tutorials?title=geovindu
http://localhost:8081/api/tutorials/published
* npm install express sequelize mysql2 cors --save
* select * from tutorials;
# CREATE TABLE IF NOT EXISTS `tutorials` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
insert into tutorials values(1,'geovindu','geovidu',1,'2025-05-04','2025-05-04');
insert into tutorials values(2,'涂聚文','涂聚文',0,'2025-05-04','2025-05-04');
* */

  

/**
 * models/index.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */

const dbConfig = require("../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,

  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);

module.exports = db;

  

 

/**
 * models/tutorial.model.js
 * node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */


module.exports = (sequelize, Sequelize) => {
  const Tutorial = sequelize.define("tutorial", {
    title: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.STRING
    },
    published: {
      type: Sequelize.BOOLEAN
    }
  });

  return Tutorial;
};

  

/**
 *  controllers/tutorial.controller.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */

const db = require("../models");
const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;

// Create and Save a new Tutorial
exports.create = (req, res) => {
  // Validate request
  if (!req.body.title) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }

  // Create a Tutorial
  const tutorial = {
    title: req.body.title,
    description: req.body.description,
    published: req.body.published ? req.body.published : false
  };

  // Save Tutorial in the database
  Tutorial.create(tutorial)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Tutorial."
      });
    });
};

// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
  const title = req.query.title;
  var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;

  Tutorial.findAll({ where: condition })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

// Find a single Tutorial with an id
exports.findOne = (req, res) => {
  const id = req.params.id;

  Tutorial.findByPk(id)
    .then(data => {
      if (data) {
        res.send(data);
      } else {
        res.status(404).send({
          message: `Cannot find Tutorial with id=${id}.`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving Tutorial with id=" + id
      });
    });
};

// Update a Tutorial by the id in the request
exports.update = (req, res) => {
  const id = req.params.id;

  Tutorial.update(req.body, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Tutorial was updated successfully."
        });
      } else {
        res.send({
          message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found or req.body is empty!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error updating Tutorial with id=" + id
      });
    });
};

// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
  const id = req.params.id;

  Tutorial.destroy({
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Tutorial was deleted successfully!"
        });
      } else {
        res.send({
          message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Tutorial with id=" + id
      });
    });
};

// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
  Tutorial.destroy({
    where: {},
    truncate: false
  })
    .then(nums => {
      res.send({ message: `${nums} Tutorials were deleted successfully!` });
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while removing all tutorials."
      });
    });
};

// find all published Tutorial
exports.findAllPublished = (req, res) => {
  Tutorial.findAll({ where: { published: true } })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

  

/**
 * routes/tutorial.routes.js
 * node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */


module.exports = app => {
  const tutorials = require("../controllers/tutorial.controller.js");

  var router = require("express").Router();

  // Create a new Tutorial
  router.post("/", tutorials.create);

  // Retrieve all Tutorials
  router.get("/", tutorials.findAll);

  // Retrieve all published Tutorials
  router.get("/published", tutorials.findAllPublished);

  // Retrieve a single Tutorial with id
  router.get("/:id", tutorials.findOne);

  // Update a Tutorial with id
  router.put("/:id", tutorials.update);

  // Delete a Tutorial with id
  router.delete("/:id", tutorials.delete);

  // Delete all Tutorials
  router.delete("/", tutorials.deleteAll);

  app.use('/api/tutorials', router);
};

  

/**
 * server.js
 * node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * */


const express = require("express");
const cors = require("cors");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

const db = require("./app/models");

db.sequelize.sync()
  .then(() => {
    console.log("Synced db.");
  })
  .catch((err) => {
    console.log("Failed to sync db: " + err.message);
  });

// // drop the table if it already exists
// db.sequelize.sync({ force: true }).then(() => {
//   console.log("Drop and re-sync db.");
// });

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

require("./app/routes/turorial.routes")(app);

// set port, listen for requests
const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

  

运行:

 node server.js

  

 

 

from:

 https://www.bezkoder.com/node-js-express-sequelize-mysql/

标签:node,const,res,WebStorm,js,tutorials,message,id,Tutorial
From: https://www.cnblogs.com/geovindu/p/18347593

相关文章

  • js学习
    变量通过prompt收集输入信息声明变量特殊情况八股文字符类型可以随时变换js中数字前补0为八进制,补0x为十六进制方法:isNaN(),如果是数字返回false,反之返回true字符串转义符字符串与别的类型拼接,拼接后为字符串字符串内设置变量布尔值数据类型,true参与运算时作为1,f......
  • JSP个人博客管理系统4n8ge(程序+源码+数据库+调试部署+开发环境)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表系统功能:用户,日志信息,个人相册,标签分类,登录签到,积分充值技术要求:    开发语言:JSP前端使用:HTML5,CSS,JSP动态网页技术后端使用SpringBoot,Spring技......
  • js文字无限循环向上滚动轮播
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><linkrel="stylesheet">......
  • JSON反序列化中的泛型问题及解决方法
    1、问题Java的泛型是编译期擦除,因此反序列化无法直接指定泛型类型:List<User>list=JsonbBuilder.create().fromJson(json,List<User>.class);编译不通过,改为List.class又达不到预期效果。2、解决办法jackson的做法:List<User>list=JsonbBuilder.create().fromJson(jso......
  • nextjs14 跨域该如何处理
    nextjs官方地址next.config.js和next.config.mjs他有什么区别next.config.js:使用的是CommonJS模块系统。这是Next.js默认的配置文件格式,也是大多数情况下使用的格式。使用require语法导入模块,使用module.exports导出对象。next.config.mjs:使用的是ESMod......
  • 部署nuxt3.js到nginx的过程
    1.先安装好nodejs的版本我centos7版本,最后发现支持nodejs-v16.20版本在[sytyuser1@syit-dev-linux-01node]$pwd/usr/local/node在 /usr/local/node  目录下载wgethttps://nodejs.org/dist/latest-v16.x/node-v16.20.2-linux-x64.tar.gz解压 tar-zxvf node-v16.20.......
  • [MRCTF2020]套娃 php字符串解析绕过,jsfuck编码
    进来看到代码<!--//1st$query=$_SERVER['QUERY_STRING'];if(substr_count($query,'_')!==0||substr_count($query,'%5f')!=0){die('Y0uareSocutE!');}if($_GET['b_u_p_t']!=='23333'......
  • 在组件外(.js文件)中使用pinia的解决方法
    Pinia是Vue3的状态管理库,它提供了一种简单而灵活的方式来管理Vue应用中的状态。通常情况下,Pinia与Vue组件紧密集成,允许你在组件内部直接使用Pinia来管理状态。然而,有时你可能需要在组件外部使用Pinia,例如在Node.js环境中或者在Vue组件之外的JavaScript文件中。......
  • JSP高血压的医疗在线问答诊断系统ft78d
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表系统功能介绍:患者,医生,医生咨询,在线问诊,医疗诊断技术要求:    开发语言:JSP前端使用:HTML5,CSS,JSP动态网页技术后端使用SpringBoot,Spring技术主数据库......
  • node.js 多版本管理 nvm的安装和使用
    #安装nvm#项目链接#https://github.com/nvm-sh/nvm#1、安装与更新使用curl或wgetcurl-o-https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh|bash#或wget-qO-https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh|bash#......