在nodejs中操纵mysql数据库
1.安装sequelize
npm install --save sequelize
2.安装数据库驱动
npm install --save mysql2
3.连接数据库
新建database文件夹,然后新建一个index.js
3.1 导入
const { Sequelize, DataTypes } = require("sequelize");
3.2编写数据库基本配置信息对象
const config = {
host: "localhost", //主机名
database: "traveldb", //使用的哪个数据库名
username: "root", //账号
password: "root", //密码
port: 3306, //端口号,mysql默认3306
};
3.3 创建orm映射对象实例,即sequelize实例
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
{
host: config.host,
dialect: "mysql",
pool: {
max: 5, //连接池最大连接数量
min: 0, //最小连接数量
idle: 10000, //如果一个线程 10秒内么有被使用过的话,就释放
},
logging: true,
}
);
3.4创建model文件夹,编写对应的模型
3.4.1创建user.js即user模型
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"user",
{
// 在这里定义模型属性
userId: {
type: DataTypes.INTEGER, //模型字段类型
primaryKey: true, //主键
autoIncrement: true, //自增长
},
username: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
tableName: "users",
timestamps: true,
}
);
return User;
};
3.5 在index.js中执行user模型的函数,并得到返回值,该返回值就是user模型对象
const User = require("./model/user")(sequelize, DataTypes);
3.6导出sequlize实例和user模型对象,方便其他地方使用
module.exports = { sequelize, User };
3.7 在app.js中执行sequelize对象的sync方法,反向映射生成表
sequelize.sync({force:true});
生成表之后请将true改为false
4.编写注册功能,回到路由文件routes/user.js
//注册
const userModel = require("../database/index").User;//导入userModel
router.post("/register", async (ctx) => {
let { username, password } = ctx.request.body;
//使用userModel的create方法插入数据
const user = await userModel.create({
username,
password,
});
//判断是否注册用户已取得
if (user) {
ctx.body = formatResponse("200", user, "success");
} else {
ctx.body = formatResponse("500", { message: "注册失败" }, "fail");
}
});
5.改写登录功能,回到路由文件routes/user.js
//登录
router.post("/login", async (ctx) => {
let { username, password } = ctx.request.body;
//根据用户名去查询用户信息
const user = await userModel.findOne({ where: { username } });
if (user) {
const accessToken =
"Bearer " +
jwt.sign(
{
userId: "0001",
username: username,
},
"zshawk1982",
{
expiresIn: 3600 * 24 * 7,
}
);
ctx.body = formatResponse("200", { accessToken, username }, "success");
} else {
ctx.body = formatResponse("500", { message: "用户名或密码错误" }, "fail");
}
});