node连接mysql

node连接mysql

下载mysql依赖

安装一下依赖包。

npm i -D mysql
npm i -D node-mysql

引入配置包

在根目录下的model/db.js文件中引入包。

const mysql = require('mysql');

const client = (sql, arg, callback) => {
  //1.创建连接
  let config = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'vue'
  })
  //2.开始连接
  config.connect()
  //3.对数据库进行增删查改
  config.query(sql, arg, (err, data) => {
    callback && callback(err, data)
  })
  //4.关闭数据库
  config.end()
}

module.exports = client;

具体使用方法

这里以一个注册登录为例展示使用方法。

var express = require('express');
var router = express.Router();
var db = require('../model/db');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/user/list', function (req, res, next) {
  db('select * from user', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      res.json({
        code: 200,
        info: '获取成功',
        data: data
      })
    }
  })
})

router.post('/user/reg', function (req, res, next) {
  console.log(req.body);
  db('select * from user where username = "' + req.body.userName + '"', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      if (data.length !== 0) {
        res.json({
          code: 109,
          info: '用户已存在!',
          data: []
        })
      } else {
        db('insert into user(id, username, password, isAdmin) values(?, ?, ?, ?)', [req.body.userId, req.body.userName, req.body.userPwd, 1], (err, data) => {
          if (err) {
            res.json({
              code: 101,
              info: '注册失败',
              data: err
            })
          }
          if (data) {
            res.json({
              code: 200,
              info: '注册成功',
              data: data
            })
          }
        })
      }
    }
  })

})

router.post('/user/login', function (req, res, next) {
  console.log(req.body);
  db('select * from user where username = "' + req.body.userName + '"', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      if (data.length !== 0) {
        if (data[0].username != req.body.userName) {
          res.json({
            code: 109,
            info: '用户昵称错误!',
            data: []
          })
         } else if (data[0].password != req.body.userPwd) {
          res.json({
            code: 109,
            info: '密码错误!',
            data: []
          })
        } else {
          res.json({
            code: 200,
            info: '登录成功!',
            data: []
          }) 
        }
      } else {
        res.json({
          code: 109,
          info: '用户不存在!',
          data: []
        })
      }
    }
  })

})

module.exports = router;

调用接口

node bin/www.js

这时候我们就可以调用接口了。

解决跨域问题方法

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods","*");//允许访问的方式
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

调用接口:一个注册案例。

这里使用axios

//用户信息
this.userInfo = {
  isLogin: true,
  userId: Date.parse(new Date()),
  userName: this.user.name,
  userPwd: this.user.pwd,
  token: 'auth' + Date.parse(new Date())
}
//注册
this.$axios.post(api.addUser, this.userInfo).then((res) => {
  if (res.data.code === 109) {
    this.isSucc = false
    this.isShowTip = true
    this.tipText = res.data.info
  } else {
    this.isSucc = true
    this.isShowTip = true
    this.tipText = res.data.info
    this.goHome(userInfo)
  }
}).catch((error) => {
  console.error(error)
})

最后

今天就到这里。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值