基礎知識推薦:http://www.runoob.com/nodejs/javascript
開發環境: windows7 mysql html
IDE: visual studio code java
代碼結構:node
connection.js mysql
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.jssql
var sqlModlue=require("./sql"); var sqlObject=new sqlModlue(); function userData(){ this.allUser=sqlObject.allUser; } module.exports=userData;
controller.jsexpress
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.htmlwindows
<!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.htmlapp
<!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 分紅 數據訪問層 業務邏輯層 控制層 以及視圖