mssql:
insert into [dbo].[tutorials]([title],[description],[published],[createdAt],[updatedAt])
values(N'涂聚文',N'涂聚文',0,'2025-05-04','2025-05-04');
go
insert into [dbo].[tutorials]([title],[description],[published],[createdAt],[updatedAt])
values(N'geovindu',N'geovindu',1,'2025-05-04','2025-05-04');
go
select * from [dbo].[tutorials]
go
insert into userinfos([userName],[userReal],[userPassword],[userIsOk],[userMail],[userMobile],[createdAt],[updatedAt]) values('geovindu','塗聚文','geovindu',1,'geovindu@163.com','13824350518','2025-07-09','2025-09-01')
go
select * from userinfos
go
/*
* 江城子 . 程序员之歌
*
* 十年生死两茫茫,写程序,到天亮。
* 千行代码,Bug何处藏。
* 纵使上线又怎样,朝令改,夕断肠。
*
* 领导每天新想法,天天改,日日忙。
* 相顾无言,惟有泪千行。
* 每晚灯火阑珊处,夜难寐,加班狂。
*
*
* @Author: geovindu
* @Date: 2024-08-14 22:25:22
* @LastEditors: geovindu
* @LastEditTime: 2024-08-14 12:21:48
* @FilePath: \vue\vuejs\nodesql\dbConfig.js
* @Description: geovindu
*
* @IDE: vscode
* @js lib: node 20 vue.js 3.0
* @database: sql server 2019
* Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved.
*/
/*
const dbConfig = {
server: "DESKTOP-OAS00A4",
port: 1433,
user: "geovindu",
password: "geovindu",
database: "geovindu",
dialect: "mssql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
*/
const dbConfig = {
HOST: "DESKTOP-OAS00A4",
PORT: "1433",
USER: "geovindu",
PASSWORD: "geovindu",
DB: "geovindu",
dialect: "mssql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
export default dbConfig;
/**
* https://nodejs.cn/api/http/http_request_url_options_callback.html
* node --trace-deprecation server //检查具体问题
* models/tutorial.model.js
*/
/**
*
* @param {*} sequelize
* @param {*} Sequelize
* @returns
*/
const Tutorial = (sequelize, Sequelize) => {
const Tutorial = sequelize.define("tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
});
return Tutorial;
};
export default Tutorial;
/*
*
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃ 神兽保佑
* ┃ ┃ 代码无bug
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
* @Author: geovindu
* @Date: 2024-08-14 10:32:27
* @LastEditors: geovindu
* @LastEditTime: 2024-08-14 22:55:55
* @FilePath: \vue\vuejs\nodesql\models\userinfo.model.js
* @Description: geovindu
*
* @IDE: vscode
* @js lib: node 20 vue.js 3.0
* @database: sql server 2019
* Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved.
*/
/**
* 参考: https://sequelize.org/docs/v6/core-concepts/assocs/ ORM 关系 一对一,一对多,多对多,多对一
*/
/**
*
* @param {*} sequelize
* @param {*} Sequelize
* @returns
*/
const UserInfo = (sequelize, Sequelize) => {
const UserInfo = sequelize.define("userInfo", {
userName: {
type: Sequelize.STRING
},
userReal:{
type:Sequelize.STRING
},
userPassword: {
type: Sequelize.STRING
},
userIsOk: {
type: Sequelize.BOOLEAN
},
userMail:
{
type:Sequelize.STRING
},
userMobile:
{
type:Sequelize.STRING
}
});
return UserInfo;
};
export default UserInfo;
/**
* https://nodejs.cn/api/http/http_request_url_options_callback.html
* node --trace-deprecation server //检查具体问题
* models/tutorial.model.js
*/
/**
*
* @param {*} sequelize
* @param {*} Sequelize
* @returns
*/
const Tutorial = (sequelize, Sequelize) => {
const Tutorial = sequelize.define("tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
});
return Tutorial;
};
export default Tutorial;
/*
* _______________#########_______________________
* ______________############_____________________
* ______________#############____________________
* _____________##__###########___________________
* ____________###__######_#####__________________
* ____________###_#######___####_________________
* ___________###__##########_####________________
* __________####__###########_####_______________
* ________#####___###########__#####_____________
* _______######___###_########___#####___________
* _______#####___###___########___######_________
* ______######___###__###########___######_______
* _____######___####_##############__######______
* ____#######__#####################_#######_____
* ____#######__##############################____
* ___#######__######_#################_#######___
* ___#######__######_######_#########___######___
* ___#######____##__######___######_____######___
* ___#######________######____#####_____#####____
* ____######________#####_____#####_____####_____
* _____#####________####______#####_____###______
* ______#####______;###________###______#________
* ________##_______####________####______________
*
* @Author: geovindu
* @Date: 2024-08-14 09:44:36
* @LastEditors: geovindu
* @LastEditTime: 2024-08-14 22:50:54
* @FilePath: \vue\vuejs\nodesql\models\index.js
* @Description: geovindu
* https://sequelize.org/docs/v7/databases/mssql/
* https://github.com/tediousjs/node-mssql
* https://github.com/tediousjs/tedious
* @IDE: vscode npm i @sequelize/mssql
* @js lib: node 20 vue.js 3.0
* @database: sql server 2019
* Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved.
*/
//import { Sequelize } from '@sequelize/core';
//import { MsSqlDialect } from '@sequelize/mssql';
import Sequelize from "sequelize";
import tutorials from "./tutorial.model.js"
import dbConfig from "../dbConfig.js";
import userinfos from "./userinfo.model.js"
/*
const sequelize = new Sequelize({
dialect: MsSqlDialect,
server: dbConfig.server,
port: dbConfig.port,
database: dbConfig.database,
authentication: {
type: 'ntlm', //default
options: {
userName: dbConfig.user,
password: dbConfig.password,
},
},
});
*/
/**
*
*
*/
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
port: dbConfig.PORT,
dialect: dbConfig.dialect,
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 = tutorials(sequelize, Sequelize); //
db.userinfos = userinfos(sequelize, Sequelize); //
export default db;
/**
* https://github.com/tediousjs/node-mssql
* controllers/tutorial.controller.js
* sql server 2019
*/
import db from "../models/index.js";
const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;
/**
*
* @param {*} req
* @param {*} res
* @returns
*/
const 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."
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const 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."
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const findOne = (req, res) => {
const id = req.params.id;
Tutorial.findByPk(id)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: "Error retrieving Tutorial with id=" + id
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const 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
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const deleteid = (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
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const 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."
});
});
};
/**
*
* @param {*} req
* @param {*} res
*/
const 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."
});
});
};
export default
{
findAllPublished,
deleteAll,
deleteid,
update,
findOne,
findAll,
create
};
/**
* https://github.com/sequelize/sequelize
* sql server 2019
* controllers/userinfo.controller.js
*/
import db from "../models/index.js";
const UserInfo = db.userinfos;
const Op = db.Sequelize.Op;
/**
* 添加记录
* @param {*} req
* @param {*} res
* @returns
*/
const usercreate = (req, res) => {
// Validate request
if (!req.body.title) {
res.status(400).send({
message: "Content can not be empty!"
});
return;
}
// Create a Tutorial
const userInfo = {
userName: req.body.userName,
userReal:req.body.userReal,
userPassword: req.body.userPassword,
userIsOk: req.body.userIsOk ? req.body.userIsOk : false,
userMail:req.body.userMail,
userMobile:req.body.userMobile
};
// Save Tutorial in the database
UserInfo.create(userInfo)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the userinfos."
});
});
};
/**
* 查看所有记录
* @param {*} req
* @param {*} res
*/
const userfindAll = (req, res) => {
const userName = req.query.userName;
var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null;
UserInfo.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving userinfos."
});
});
};
/**
* 查找一条记录
* @param {*} req
* @param {*} res
*/
const userfindOne = (req, res) => {
const id = req.params.id;
UserInfo.findByPk(id)
.then(data => {
if (data) {
res.send(data);
} else {
res.status(404).send({
message: `Cannot find userinfos with id=${id}.`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error retrieving userinfos with id=" + id
});
});
};
/**
* 更新记录
* @param {*} req
* @param {*} res
*/
const userupdate = (req, res) => {
const id = req.params.id;
UserInfo.update(req.body, {
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "usrinfos was updated successfully."
});
} else {
res.send({
message: `Cannot update userinfos with id=${id}. Maybe userinfos was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating userinfos with id=" + id
});
});
};
/**
* 删除了一条记录
* @param {*} req
* @param {*} res
*/
const userdeleteid = (req, res) => {
const id = req.params.id;
UserInfo.destroy({
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "userinfos was deleted successfully!"
});
} else {
res.send({
message: `Cannot delete userinfos with id=${id}. Maybe userinfos was not found!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete userinfos with id=" + id
});
});
};
/**
* 删除所有记录
* @param {*} req
* @param {*} res
*/
const userdeleteAll = (req, res) => {
UserInfo.destroy({
where: {},
truncate: false
})
.then(nums => {
res.send({ message: `${nums} userinfos were deleted successfully!` });
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while removing all userinfos."
});
});
};
/**
* 查找有效的会员记录
* @param {*} req 变量
* @param {*} res 变量
*/
const findAlluserIsOk = (req, res) => {
UserInfo.findAll({ where: { userIsOk: true } })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving userinfos."
});
});
};
// 使用 ES6 的默认导出语法,直接导出包含所有函数的对象
export default
{
findAlluserIsOk,
userdeleteAll,
userdeleteid,
userupdate,
userfindOne,
userfindAll,
usercreate
};
/*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃
* ┃ ┃ + 神兽保佑
* ┃ ┃ 代码无bug
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*
*
* @Author: geovindu
* @Date: 2024-08-14 22:51:57
* @LastEditors: geovindu
* @LastEditTime: 2024-08-14 22:57:11
* @FilePath: \vue\vuejs\nodesql\routes\turorial.routes.js
* @Description: geovindu
*
* @IDE: vscode
* @js lib: node 20 vue.js 3.0
* @database: sql server 2019
* Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved.
*/
import express from "express"
import tutorials from "../controllers/tutorial.controller.js"
import userinfos from "../controllers/userinfo.controller.js"
const routes = app => {
var router = express.Router();
// Create a new Tutorial
//app.post("/", Tutorial.findAll);
router.post("/tutorials",tutorials.create)
router.post("/user",userinfos.usercreate)
// Retrieve all Tutorials
router.get("/tutorials", tutorials.findAll);
router.get("/user", userinfos.userfindAll);
/**/
// Retrieve all published Tutorials
router.get("/tutorials/published", tutorials.findAll);
router.get("/user/userIsOk", userinfos.findAlluserIsOk);
// Retrieve a single Tutorial with id
router.get("/user/:id", userinfos.userfindOne);
router.get("tutorials/:id", tutorials.findOne);
// Update a Tutorial with id
router.put("tutorials/:id", tutorials.update);
router.put("/user/:id", userinfos.userupdate);
// Delete a Tutorial with id
router.put("tutorials/:id", tutorials.deleteid);
router.put("/user/:id", userinfos.userdeleteid);
// Delete all Tutorials
router.put("/tutorials", tutorials.deleteAll);
router.put("/user", userinfos.userdeleteAll);
//app.use('/api/tutorials', router);
app.use('/api',router);
};
export default routes;
/*
* ┌───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
* │Esc│ │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│ ┌┐ ┌┐ ┌┐
* └───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘ └┘ └┘ └┘
* ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
* │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
* ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
* │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ | \ │ │Del│End│PDn│ │ 7 │ 8 │ 9 │ │
* ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
* │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter │ │ 4 │ 5 │ 6 │ │
* ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤ ┌───┐ ├───┼───┼───┼───┤
* │ Shift │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│ Shift │ │ ↑ │ │ 1 │ 2 │ 3 │ │
* ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
* │ Ctrl│ │Alt │ Space │ Alt│ │ │Ctrl│ │ ← │ ↓ │ → │ │ 0 │ . │←─┘│
* └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
*
* @Author: geovindu
* @Date: 2024-08-14 22:53:38
* @LastEditors: geovindu
* @LastEditTime: 2024-08-14 22:34:37
* @FilePath: \vue\vuejs\nodesql\server.js
* @Description: geovindu
* backend frontend
* @IDE: vscode
* @js lib: node 20 vue.js 3.0
* @database: sql server 2019
* Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved.
*/
import express from "express";
import cors from "cors";
import routes from "./routes/turorial.routes.js"
import db from "./models/index.js"
const app = express();
var corsOptions = {
origin: "http://localhost:8083"
};
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 }));
//http://localhost:8080/models
///http://localhost:8082/api/tutorials
//http://localhost:8082/api/tutorials/2
//http://localhost:8082/api/user
//const db = require("./app/models");
db.sequelize.sync()
.then(() => {
console.log("Synced db.");
})
.catch((err) => {
console.log("Failed to sync db: " + err.message);
});
routes(app); //
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8082;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
运行:
node server
也可以运行,查看BUG
node --trace-deprecation server
WebStorm 2023.1:
/**
* config/db.config.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious cors
* */
/**
*
* @type {{dialect: string, PORT: string, PASSWORD: string, pool: {min: number, max: number, idle: number, acquire: number}, HOST: string, USER: string, DB: string}}
*/
module.exports = {
HOST: "DESKTOP-OAS00A4",
PORT: "1433",
USER: "geovindu",
PASSWORD: "geovindu",
DB: "geovindu",
dialect: "mssql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
/**
@description WebStorm
@author geovindu geovindu
@project vuedemo
@package
@file userinfo.model.js
@ide webstorm 2023.1
@database sql server 2019
@dev node 20 vue.js 3.0
@date Created in 20:50 2024/08/15
@edate eddit in
*/
/**
* userInfo 实体类
* @param sequelize
* @param Sequelize
* @returns {*}
*/
module.exports = (sequelize, Sequelize) => {
const UserInfo = sequelize.define("userInfo", {
userName: {
type: Sequelize.STRING
},
userReal:{
type:Sequelize.STRING
},
userPassword: {
type: Sequelize.STRING
},
userIsOk: {
type: Sequelize.BOOLEAN
},
userMail:
{
type:Sequelize.STRING
},
userMobile:
{
type:Sequelize.STRING
}
});
return UserInfo;
};
/**
* models/tutorial.model.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious cors
* */
/**
*
* @param sequelize
* @param Sequelize
* @returns {*}
*/
module.exports = (sequelize, Sequelize) => {
const Tutorial = sequelize.define("tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
});
return Tutorial;
};
/**
@description WebStorm
@author geovindu geovindu
@project vuedemo
@package
@file userinfo.model.js
@ide webstorm 2023.1
@database sql server 2019
@dev node 20 vue.js 3.0
@date Created in 20:50 2024/08/15
@edate eddit in
*/
/**
* userInfo 实体类
* @param sequelize
* @param Sequelize
* @returns {*}
*/
module.exports = (sequelize, Sequelize) => {
const UserInfo = sequelize.define("userInfo", {
userName: {
type: Sequelize.STRING
},
userReal:{
type:Sequelize.STRING
},
userPassword: {
type: Sequelize.STRING
},
userIsOk: {
type: Sequelize.BOOLEAN
},
userMail:
{
type:Sequelize.STRING
},
userMobile:
{
type:Sequelize.STRING
}
});
return UserInfo;
};
/**
* models/index.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious 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,
port: dbConfig.PORT,
dialect: dbConfig.dialect,
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;
//关联对象 tutorials 表
db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);
//关联对象 userinfos 表
db.userinfos = require("./userinfo.model.js")(sequelize, Sequelize);
module.exports = db;
/**
@description WebStorm
@author geovindu geovindu
@project vuedemo
@package
@file userinfo.controller.js
@ide webstorm 2023.1
@database mysql 8.0 sql server 2019
@dev node 20 vue.js 3.0
@date Created in 20:56 2024/08/15
@edate eddit in
*/
const db = require("../models");
const UserInfo = db.userinfos;
const Op = db.Sequelize.Op;
/**
* 添加记录
* @param {*} req
* @param {*} res
* @returns
*/
exports.usercreate = (req, res) => {
// Validate request
if (!req.body.title) {
res.status(400).send({
message: "Content can not be empty!"
});
return;
}
// Create a Tutorial
const userInfo = {
userName: req.body.userName,
userReal:req.body.userReal,
userPassword: req.body.userPassword,
userIsOk: req.body.userIsOk ? req.body.userIsOk : false,
userMail:req.body.userMail,
userMobile:req.body.userMobile
};
// Save Tutorial in the database
UserInfo.create(userInfo)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the userinfos."
});
});
};
/**
* 查看所有记录
* @param {*} req
* @param {*} res
*/
exports.userfindAll = (req, res) => {
const userName = req.query.userName;
var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null;
UserInfo.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving userinfos."
});
});
};
/**
* 查找一条记录
* @param {*} req
* @param {*} res
*/
exports.userfindOne = (req, res) => {
const id = req.params.id;
UserInfo.findByPk(id)
.then(data => {
if (data) {
res.send(data);
} else {
res.status(404).send({
message: `Cannot find userinfos with id=${id}.`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error retrieving userinfos with id=" + id
});
});
};
/**
* 更新记录
* @param {*} req
* @param {*} res
*/
exports.userupdate = (req, res) => {
const id = req.params.id;
UserInfo.update(req.body, {
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "usrinfos was updated successfully."
});
} else {
res.send({
message: `Cannot update userinfos with id=${id}. Maybe userinfos was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating userinfos with id=" + id
});
});
};
/**
* 删除了一条记录
* @param {*} req
* @param {*} res
*/
exports.userdeleteid = (req, res) => {
const id = req.params.id;
UserInfo.destroy({
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "userinfos was deleted successfully!"
});
} else {
res.send({
message: `Cannot delete userinfos with id=${id}. Maybe userinfos was not found!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete userinfos with id=" + id
});
});
};
/**
* 删除所有记录
* @param {*} req
* @param {*} res
*/
exports.userdeleteAll = (req, res) => {
UserInfo.destroy({
where: {},
truncate: false
})
.then(nums => {
res.send({ message: `${nums} userinfos were deleted successfully!` });
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while removing all userinfos."
});
});
};
/**
* 查找有效的会员记录
* @param {*} req 变量
* @param {*} res 变量
*/
exports.findAlluserIsOk = (req, res) => {
UserInfo.findAll({ where: { userIsOk: true } })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving userinfos."
});
});
};
/**
* controllers/tutorial.controller.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious 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 => {
res.send(data);
})
.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/turorial.routers.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious cors
* ///http://localhost:8082/api/tutorials
* //http://localhost:8082/api/tutorials/2
* //http://localhost:8082/api/userinfos
* */
/**
*
* @param app
*/
module.exports = app => {
const tutorials = require("../controllers/tutorial.controller.js");
const userinfos=require("../controllers/userinfo.controller")
var router = require("express").Router();
// Create a new Tutorial
router.post("/tutorials/", tutorials.create);
//Create a new userinfo
router.post("/userinfos/", userinfos.usercreate);
// Retrieve all Tutorials
router.get("/tutorials/", tutorials.findAll);
//Retrieve all userinfos
router.get("/userinfos/", userinfos.userfindAll);
// Retrieve all published Tutorials
router.get("/tutorials/published", tutorials.findAllPublished);
//Retrieve all published userinfos
router.get("/userinfos/", userinfos.findAlluserIsOk);
// Retrieve a single Tutorial with id
router.get("/tutorials/:id", tutorials.findOne);
//Retrieve a single userinfos with id
router.get("/userinfos/:id", userinfos.userfindOne);
// Update a Tutorial with id
router.put("/tutorials/:id", tutorials.update);
//Update a userinfos with id
router.put("/userinfos/:id", userinfos.userupdate);
// Delete a Tutorial with id
router.delete("/tutorials/:id", tutorials.delete);
//Delete a userinfos with id
router.delete("/userinfos/:id", userinfos.userdeleteid);
// Delete all Tutorials
router.delete("/tutorials/", tutorials.deleteAll);
//Delete all userinfos
router.delete("/userinfos/", userinfos.userdeleteAll);
app.use('/api', router);
};
/**
* server.js
* node 20 vue.js 3.0
* ide: WebStorm 2023.1
* mssql 2019
* npm install express sequelize tedious cors
* */
const express = require("express");
// const bodyParser = require("body-parser"); /* deprecated */
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8083"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json()); /* bodyParser.json() is deprecated */
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true })); /* bodyParser.urlencoded() is deprecated */
const db = require("./models");
db.sequelize.sync();
// // 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("./routes/turorial.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8082;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
运行:
node server
自动创建表