前端地址为:https://blog.csdn.net/renxingwu2008/article/details/123706811
mkdir org_hr
cd org_hr
npm init
Press ^C at any time to quit.
package name: (org_hr)
version: (1.0.0)
description: this is a project
entry point: (index.js) server.js
test command:
git repository:
keywords:
author: renxws
license: (ISC)
About to write to F:\WebProjects\NodeJS\02_Base\org_user\package.json:
{
"name": "org_hr",
"version": "1.0.0",
"description": "this is a project",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "renxws",
"license": "ISC"
}
Is this OK? (yes) yes
npm install express sequelize mysql2 body-parser cors --save
server.js
const express = require("express")
const bodyParser = require("body-parser")
const cors = require("cors")
const app = express()
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions))
// 解析application/json的请求
app.use(bodyParser.json())
// 解析application/x-www-form-urlencoded的请求
app.use(bodyParser.urlencoded({ extended: true }))
// 根目录路由
app.get("/", (req, res) => {
res.json({ message: "Hello World!!!" })
})
// 设置端口, 监听请求
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器已启动...,端口为: ${PORT}.`)
})
node server.js
node server.js
服务器已启动...,端口为: 3000.
app
目录,app
目录下创建config
目录,目录下创建数据库配置文件db.config.js
mkdir app
cd app
mkdir config
module.exports = {
// 数据库IP
HOST: "127.0.0.1",
// 数据库账户名
USER: "root",
// 数据库密码
PASSWORD: "root",
// 账户名
DB: "dbtest",
// 数据库方言
dialect: "mysql",
pool: {
// 连接池最大连接数
max: 5,
// 连接池最小连接数
min: 0,
// 在抛出错误之前,该池将尝试获取连接的最长时间(以毫秒为单位)
acquire: 30000,
// 在释放连接之前,连接可以处于空闲状态的最长时间(以毫秒为单位)
idle: 10000
}
}
app
目录下创建models
目录mkdir models
models
目录下创建index.js
文件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.users = require("./user.model.js")(sequelize, Sequelize);
module.exports = db;
server.js
中添加调用其方法:const db = require("./app/models");
db.sequelize.sync();
const express = require("express")
const bodyParser = require("body-parser")
const cors = require("cors")
const app = express()
var corsOptions = {
origin: "http://localhost:8080"
};
app.use(cors(corsOptions))
// 解析application/json的请求
app.use(bodyParser.json())
// 解析application/x-www-form-urlencoded的请求
app.use(bodyParser.urlencoded({ extended: true }))
// 设置models调用
const db = require("./app/models");
db.sequelize.sync();
/**
* 通过models实例创建数据库表时使用
db.sequelize.sync({ force: true }).then(() => {
console.log("删除并且重新同步数据库!!!");
});
*/
// 根目录路由
app.get("/", (req, res) => {
res.json({ message: "Hello World!!!" })
})
// 设置端口, 监听请求
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器已启动...,端口为: ${PORT}.`)
})
models
目录下定义Sequelize Modeluser.model.js
,字段对应着数据库表中的列名,其中id
、updatedAt
和updatedAt
三字段不用考虑module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("user", {
userId: {
type: Sequelize.STRING
},
userName: {
type: Sequelize.STRING
},
userPass: {
type: Sequelize.STRING
},
userCN: {
type: Sequelize.STRING
},
sex: {
type: Sequelize.STRING
},
mobile: {
type: Sequelize.STRING
},
telNo: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
address: {
type: Sequelize.STRING
},
roomNO: {
type: Sequelize.STRING
},
effectTime: {
type: Sequelize.DATE
},
description: {
type: Sequelize.STRING
},
isEffective: {
type: Sequelize.BOOLEAN
}
});
return User;
};
app
目录下创建controllers
目录,创建文件user.controller.js
,方法尚未写全const db = require("../models");
const User = db.user;
// 创建并且保存一个用户
exports.create = (req, res) => {
// 请求验证
if (!req.body.userName || !req.body.userCN || !req.body.mobile || !req.body.address) {
res.status(400).send({
message: "该内容不能为空!"
});
return;
}
// 创建一个用户实例
const user = {
userId: req.body.userId,
userName: req.body.userName,
userPass: req.body.userPass,
userCN: req.body.userCN,
sex: req.body.sex,
mobile: req.body.mobile,
telNo: req.body.telNo,
email: req.body.email,
address: req.body.address,
roomNO: req.body.roomNO,
effectTime: req.body.effectTime,
description: req.body.description,
isEffective: req.body.isEffective ? req.body.isEffective : false,
createdAt: new Date(),
updatedAt: new Date()
};
// 保存用户实例到数据库
User.create(user)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "创建失败!"
});
});
};
/**
*
* @param {*} req
* @param {*} res
*
* 测试创建数据
* {
"userId": "10000007",
"userName": "zhaoyun",
"userPass": "zhaoyun",
"userCN": "赵云",
"sex": "男",
"mobile": "18640283517",
"telNo": "1239456",
"email": "[email protected]",
"address": "沈阳市和平区英雄胡同666号",
"roomNO": "1007",
"effectTime": "2030-12-31 15:51:12",
"description": "三国演义蜀国大将之一",
"isEffective": "1"
}
*/
// 查找所有用户
exports.findAll = (req, res) => {
const userName = req.query.userName;
var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null;
User.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "查找失败!!!"
});
});
};
// 根据ID查找一个用户
exports.findOne = (req, res) => {
};
// 根据ID更新一个用户
exports.update = (req, res) => {
const id = req.params.id;
User.update(req.body, {
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "用户更新成功!"
});
} else {
res.send({
message: `不能更新ID为:${id}的用户,请核实用户信息!`
});
}
})
.catch(err => {
res.status(500).send({
message: `更新ID为:${id}的用户失败!`
});
});
};
// 删除一个用户
exports.delete = (req, res) => {
const id = req.params.id;
console.log(id)
User.destroy({
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "用户删除成功!"
});
} else {
res.send({
message: `删除ID为:${id}的用户失败,请确认该用户是否存在!`
});
}
})
.catch(err => {
res.status(500).send({
message: `不能删除ID为: + ${id}的用户!`
});
});
};
// 删除所有用户
exports.deleteAll = (req, res) => {
};
// 查询有效的用户
exports.findAllPublished = (req, res) => {
};
app
目录下创建routes
目录,创建文件user.routes.js
const { user } = require("../models/index.js");
module.exports = app => {
const users = require("../controllers/user.controller.js");
var router = require("express").Router();
// 创建一个用户
router.post("/", users.create);
// 查找全部用户
router.get("/", users.findAll);
// 根据用户ID查找用户
router.get("/:id", users.findOne);
// 根据用户ID更新用户信息
router.put("/:id", users.update);
// 根据ID删除指定用户
router.delete("/:id", users.delete);
// 删除所有用户
router.delete("/", users.deleteAll);
app.use('/api/users', router);
};
server.js
中添加路由配置require("./app/routes/user.routes")(app);
server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8080"
};
app.use(cors(corsOptions));
// 解析内容类型为:application/json 的请求
app.use(express.json());
// 解析内容类型为:application/x-www-form-urlencoded 的请求
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
db.sequelize.sync();
/**
* 通过models实例创建数据库表时使用
db.sequelize.sync({ force: true }).then(() => {
console.log("删除并且重新同步数据库!!!");
});
*/
// 简单路由
app.get("/", (req, res) => {
res.json({ message: "欢迎来到我的应用!!!" });
});
require("./app/routes/user.routes")(app);
// 设置端口, 监听请求
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器正在运行,端口为: ${PORT}.`);
});
控制台输入:node server.js
(node:10596) [SEQUELIZE0004] DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.
(Use `node --trace-deprecation ...` to show where the warning was created)
服务器正在运行,端口为: 3000.
Executing (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `userId` VARCHAR(255), `userName` VARCHAR(255), `userPass` VARCHAR(255), `userCN` VARCHAR(255), `sex` VARCHAR(255), `mobile` VARCHAR(255), `telNo` VARCHAR(255), `email` VARCHAR(255), `address` VARCHAR(255), `roomNO` VARCHAR(255), `effectTime` DATETIME, `description` VARCHAR(255), `isEffective` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `users`
浏览器访问:
http://localhost:3000/api/users
注意:只写了部分方法,方法写的不全