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)
})
最后
今天就到这里。