Node.js 學習(四)——實現(xiàn)用戶登錄功能
Node.js學習(四)——實現(xiàn)用戶登錄功能
本文目的
了解node.js的整套前后臺流程
具體實現(xiàn)
使用express創(chuàng)建項目
express -e nodejs-login-demo
修改package.json文件
添加mysql,bootstrap和jquery模塊,用的是最新版本,所以寫的是latest
{
"name": "nodejs-login-demo",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"ejs": "~2.4.1",
"express": "~4.13.4",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0",
"mysql":"latest",
"bootstrap":"latest",
"jquery":"latest"
}
}
將jquery和bootstrap拷貝的public下
參考http://blog.csdn.net/flygoa/article/details/52677652
登錄頁面
修改index.ejs文件
用戶登錄
登錄demo
登錄接口
修改routes(路由)目錄下index.js文件,添加一下內(nèi)容
//登錄接口
router.post('/login', function(req, res, next) {
var name = req.body.username;
var pwd = req.body.password;
var mysql = require('mysql');
//配置連接
var connection = mysql.createConnection({
host: 'localhost',//主機地址
user: 'root',//登錄名
password: '',//密碼,我這里是空
database:'nodejsdb'//數(shù)據(jù)庫
});
//輸入驗證
if(!name || name == "") {
console.log("用戶名不能為空");
res.send('用戶名不能為空');
return;
}
if(!pwd || pwd == "") {
console.log("密碼不能為空");
res.send('密碼不能為空');
return;
}
//查庫比較
connection.connect();
connection.query('SELECT COUNT(*) checkNum FROM `t_user` WHERE name = \''+name+'\' AND psw =\''+ pwd +'\'', function(err, rows, fields) {
if (err) throw err;
var checkNum = rows[0].checkNum;
console.log('結(jié)果為: ', rows[0].checkNum);
if(checkNum == 0){
console.log('賬號或密碼不正確');
res.send('賬號或密碼不正確');
}else{
console.log('登錄成功');
//返回結(jié)果
res.send('登錄成功,賬號密碼為:'+name+"---"+pwd);
}
});
//關閉連接
connection.end();
});
頁面及效果
示例中使用的是res.send()方法輸出一段字符串
登錄頁面
登錄成功頁面
登錄失敗提醒
參考
express中文api(感謝博主分享):http://blog.csdn.net/zhx6044/article/details/50179607
評論
圖片
表情
