基础知识推荐:http://www.runoob.com/nodejs/
开发环境: windows7 mysql
IDE: visual studio code
代码结构:
connection.js
var mysql=require("mysql");
function connection(){
this.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database : 'Sws'
});
}
module.exports=connection;
sql.js
var connectionModlue=require("./connection");
var connectionObject=new connectionModlue();
function dataBase(){
var connection=connectionObject.connection;
connection.connect();
var sql = 'SELECT * FROM user';
this.allUser=connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
});
connection.end();
}
module.exports=dataBase;
service.js
var sqlModlue=require("./sql");
var sqlObject=new sqlModlue();
function userData(){
this.allUser=sqlObject.allUser;
}
module.exports=userData;
controller.js
var http=require("http");
var url=require("url");
var bodyParser = require('body-parser');
var express=require("express");
var userService=require("./service");
var app=express();
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
app.post('/login',urlencodedParser,function(req,res){
var userObject=new userService();
var allUser=userObject.allUser._results[0];
var userName=req.body.userName;
var password=req.body.password;
for(var i in allUser){
if(userName==allUser[i].NAME&&password==allUser[i].PASSWORD){
res.set("isLogin",true);
res.sendFile( __dirname + "/" + "success.html");
}
}
res.set("isLogin",false);
res.sendFile( __dirname + "/" + "failer.html");
});
app.listen(8081);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/script"src=""></script>
<title>登陆</title>
<script type="text/script">
</script>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="userName"/><br/>
<input type="password" name="password">
<input type="submit" value="登陆">
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>首页</title>
</head>
<body>
<p>登陆成功</p>
</body>
</html>
failer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>首页</title>
</head>
<body>
<p>登陆失败</p>
</body>
</html>
上面就是完整的node.js的登陆功能实现了,因为自己是java程序员所以 按照 java的分层模式把node 分成 数据访问层 业务逻辑层 控制层 以及视图