在nodejs中操纵mysql数据库

在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");
  }
});
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值