溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Node.js利用Express如何實現(xiàn)用戶注冊登陸功能

發(fā)布時間:2020-10-28 02:41:33 來源:億速云 閱讀:188 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)Node.js利用Express如何實現(xiàn)用戶注冊登陸功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

環(huán)境

  • OS: Win10
  • Node.js: v12.19.0
  • Express: v4.17.1
  • Yarn: v1.22.10
  • 使用VScode IDE
  • body-parser:1.19.0
  • mysql: 2.18.1
  • MySQL Server:5.7
  • SQLyog:V12.9

準(zhǔn)備

首先在Win10上安裝Mysql,一路Next就行。安裝完成使用SQLyog連接MySQL Server。連接成功需要創(chuàng)建數(shù)據(jù)庫和數(shù)據(jù)表

Schema:

CREATE TABLE user (
username char(20) NOT NULL,
password char(20) NOT NULL,
email char(30) DEFAULT NULL,
address char(20) DEFAULT NULL,
phonenumber char(20) DEFAULT NULL,
logintime int(20) DEFAULT NULL,
id int(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
KEY username (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

實戰(zhàn)

前端

3個page, login.html, register.html.

index.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
			<title>登陸注冊</title>
			<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
		</head>
		<body>
			<a href="./register.html" rel="external nofollow" >注冊</a>
			<a href="./login.html" rel="external nofollow" >登錄</a>
		</body>
	</head>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
			<title>登陸注冊</title>
			<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
		</head>
		<body>
			<form action="/login" method="GET" >  
				<label for="">賬號:</label> 
				<input name="user" type="text" placeholder="請輸入賬號"> 
				<br> 
				<label for="">密碼:</label> 
				<input type="password" name="password" placeholder="請輸入密碼"> 
				<br>
				<input type="submit" value="登錄">
			</form>
		</body>
	</head>
</html>

register.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
			<title>登陸注冊</title>
			<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
		</head>
		<body>
			<form action="/register" method="POST">
				<label for="">賬號:</label> 
				<input name="user" type="text" placeholder="請輸入賬號">
				<br> 
				<label for="">密碼:</label> 
				<input name="psw" type="password" placeholder="請輸入密碼"> 
				<br> 
				<label for="">重復(fù)密碼:</label> 
				<input name="pswa" type="password" placeholder="請重復(fù)密碼"> 
				<br> 
				<input type="submit" value="注冊">
			</form>
		</body>
	</head>
</html>

后端 server.js

var express = require("express");
var bodyParser = require("body-parser");
var router = require("./routers");

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use('/', router);

module.exports = app;

Router

router/index.js, 調(diào)用封裝好的數(shù)據(jù)庫接口:queryUer, addUser

const express=require("express");
const dao = require("../dao/db");

const router=express.Router();

router.get("/login", function(req,res){
 console.dir(req.query);
 try{
  dao.queryUser({username:req.query.user},function(err,record){
   if(err){
    console.log(err);
    throw error;
   }
   console.log(record);
   if(record && record.password == req.query.password){
    res.send(`${req.query.user}:登陸成功`);
   }else{
    res.send(`${req.query.user}:登陸失敗,檢查登陸信息是否正確`);
   }
  });
 } catch(error){
  console.log(error);
  res.send(`${req.body.user}: 登陸失敗`);
 } 
})

router.post("/register", function(req,res){
 console.dir(req.body); 
 try{
  if(req.body.psw == req.body.pswa){
   dao.addUser({username:req.body.user,password:req.body.psw});
   res.send(`${req.body.user}: 注冊成功`);
  } else {
   console.log(error);
   res.send(`${req.body.user}: 注冊失敗:,檢查登陸信息是否正確`);
  }  
 } catch(error){
  console.log(error);
  res.send(`${req.body.user}: 注冊失敗`);
 }
 
})
module.exports = router;

數(shù)據(jù)庫接口db.js

dao/db.js

var mysqlClient= require("./mysql");

function addUser (userInfo,callabck){
 console.log("addUser:"+ userInfo);
 var sql= `insert into user(username,password) values('${userInfo.username}','${userInfo.password}')`;
 console.log("sql:"+ sql);
 mysqlClient(sql,function(err,rows){
  if(err){
   console.log("err:"+err);
   callabck(err,null);
  } else{
   console.log("addUser result:");
   console.log(rows);
   callabck(null,rows);
  }
 })
}

function queryUser (userInfo,callabck){
 console.log("queryUser:"+ userInfo);
 var sql= `select * from user where username='${userInfo.username}'`;
 console.log("sql:"+ sql);
 mysqlClient(sql, function(err,rows){
  if(err){
   console.log("err:"+err);
   callabck(err,null);
  } else{   
   rows && rows.length>0 &#63; callabck(null,rows[0]): callabck(null,null);
  }
 })
}
exports.addUser = addUser;
exports.queryUser = queryUser;

dao/mysql.js

const mysql = require("mysql");
const pool = mysql.createPool({
 host:"localhost",
 user:"root",
 password:"*****",
 database:"test"
});

function query(sql,callback){
 pool.getConnection(function(err,connection){
  if(err){
   callback(err,null);
   return
  }
  connection.query(sql, function (err,rows) {   
   callback(err,rows);
   connection.release();
  });
 });
}

module.exports = query;

mysql module

yarn add mysql

運行index.js

cd src/ && node index.js

結(jié)果及演示

瀏覽器看效果及整個過程。
Node.js利用Express如何實現(xiàn)用戶注冊登陸功能

看完上述內(nèi)容,你們對Node.js利用Express如何實現(xiàn)用戶注冊登陸功能有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI