1. 程式人生 > >百度t7 教程 node 初步4 使用者登入和 註冊1

百度t7 教程 node 初步4 使用者登入和 註冊1

基本架構 回顧: 

index.js

let http = require('http')
let fs = require('fs')
let url = require('url')
let mysql=require('mysql')


//   建立個 伺服器
let server = http.createServer(function(req,res){

	// 1, 拆解url 
	// es6 解構賦值  
	let {pathname,query}  = url.parse(req.url,true);
	let {username,password}= query;

	console.log(pathname,username,password)
	if(pathname=='/login'){
			res.write('login')
			res.end()		
	}else if(pathname=='/reg'){
		res.write('reg')
		res.end()
	}else if(pathname=='/index.html'){
		res.write('index.html')	
		res.end()
	}	
});


// 監聽3000 埠 
server.listen(3000)


瀏覽器地址 是 localhost:3000/index.html  則打印出 index.html

若是 localhost:3000/reg  則打印出 reg

若是 localhost:3000/login  則打印出 login

--> next  我們要把index.html 做為一個 檔案返回!!

改進  後端程式碼:  

//   建立個 伺服器
let server = http.createServer(function(req,res){

	// 1, 拆解url 
	// es6 解構賦值  
	let {pathname,query}  = url.parse(req.url,true);
	let {username,password}= query;

	console.log(pathname,username,password)
	if(pathname=='/login'){
			res.write('login')
			res.end()		
	}else if(pathname=='/reg'){
		res.write('reg')
		res.end()
	}else if(pathname=='/index.html'){
		//讀取檔案的操作: 
		fs.readFile('./public/index.html',function(err,data){
			if(err){
				//若 讀取  檔案失敗,
				res.writeHeader(404)
				res.write('檔案不存在')
				res.end();
			}else{
				res.write(data.toString())
				res.end();
			}
		})
	}	
});

若瀏覽器是 localhost:3000/index.html  則讀取

public  資料夾下index.html 返回

顯示結果為:

index.html 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>index</title>
</head>
<body>
	
	<h1>歡迎來到主頁!!</h1>

	<p>
	這是 靜態頁面要直接返回
	要多敲, 因為多敲才能進步 
	不要眼高手低,要多行動
	千萬要多心動,只有動起來,才有效果
	</p>
</body>
</html>

-->next 

上面我們也能返回靜態頁面 了,也 把基本 架構搭建好了,下面  我們來看下,基本 登入和註冊邏輯 

使用者登入和註冊的簡單邏輯, 這個要手寫完成 !!              //  前後端打交道,

        必定要定義 前後端介面!

        前端 ,  登入的表單項,然後用          jQuery 的ajax 去提交資料,

        然後,後端接受收資料,處理,然後把返回資訊交給

        ajax ,然後 提示給 使用者進行  了

        view ----->  node  ---> db

          下面是定義介面           後臺,返回給前臺一個 json            {               code :0;               msg:''           }

          code==0 表明 正常返回,沒有任何錯誤           code!=0; 表明 有 錯誤,此時提示msg的資訊 _____________________________________________________           註冊的簡單邏輯           前臺 傳送 給後臺,              1, username            2, password           後臺接收 後,進行對應的處理!

          let {username,password} = query;

          1,校驗 ,

          2    校驗成功後,               去伺服器端去查,是否使用者已經註冊過               若註冊過,給前臺 返回 使用者名稱已經存在 

              若不存在,               則插入到資料庫中,若插入不成功               則告訴使用者, 資料庫出錯                若插入成功,則 

          修改下 登入標記,然後提示使用者註冊成功!

              - —— --- --------------

              使用者登入的邏輯                1,校驗               2, 去資料庫查是否 使用者名稱存在,若不 存在,則 提示使用者名稱不 存在               若存在,則繼續 去查密碼是否正確,若不正確,則提示使用者密碼 不 正確               若使用者名稱密碼都正確,則 提示 登入成功!

行,下一篇,就 按照上面的一點點敲!