nodejs连接数据库
var express = require("express");
var query = require("querystring");
var mysql = require("mysql");
var con = require("./connect.js");
var app = express();
app.listen("8000",function () {
console.log("port is 8000,server is start");
})
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
next();
});
app.post("/login",function(req,res){
var reqData = "";
req.on("data",function (data) {
reqData += data;
})
req.on("end",function () {
//console.log(reqData);
let param = query.parse(reqData);
let username = param.name,
password = param.password;
//通过查询表来判断是否有该用户
con.connect(function (db) {
if(db){
// 数据库链接成功
var sql = `SELECT * FROM USER where User like '${username}' and Password like '${password}'`;
db.query(sql,function (err,results,fields) {
if (err) {
console.log(err);
return;
}
// 没有查询到记录时,则results = []
//console.log(results);
//console.log(results.length);
if(results.length < 1){
res.send("用户名或者密码错误!");
} else {
res.send("登录成功!");
//关闭数据库连接
//db.end();
db.destroy();
}
})
}else{
// 数据库链接失败
console.log('数据库链接失败'+db);
}
});
})
})
connection.js
function connect(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database:'mysql'
});
//connection.escape();
connection.connect(function (err) {
if (err) {
callback(null);
}else{
callback(connection);
}
});
}
module.exports.connect = connect;