這篇文章主要介紹“nodejs怎么實現登陸驗證功能”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“nodejs怎么實現登陸驗證功能”文章能幫助大家解決問題。
登陸驗證需要提交數據,一種使用form表單提交數據,另一種使用原生js提交數據
搭建后臺服務器
const express = require('express') const app = express() const bodyparser = require('body-parser') //掛載參數處理的中間件 //extended:false 表示使用系統模塊querystring來處理 將字符串轉化為對象 app.use(bodyparser.urlencoded({extended:false})) //掛載內置中間件處理靜態文件 app.use(express.static('public')) //使用form表單提交 app.post('/login',(req,res)=>{ //因為是post,所以使用body let data = req.body; //判斷用戶名和密碼 if(data.username=='admin'&&data.password=='123'){ res.send('登陸成功') }else{ res.send('登陸失敗') } }) app.listen(3000,()=>{ console.log('running....'); })
public目錄下的login.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="http://localhost:3000/login" method="post"> 用戶名: <input type="text" name="username" id="use"><br> 密碼: <input type="password" name="password" id="pwd"><br> <!-- <input type="submit" value="登錄"> --> <input type="button" value="登錄" id="btn"> </form> </body> </html>
但該方法已經很很少使用了,現在主要使用ajax請求后臺接口地址
const express = require('express') const app = express() const bodyparser = require('body-parser') //掛載參數處理的中間件 //extended:false 表示使用系統模塊querystring來處理 將字符串轉化為對象 app.use(bodyparser.urlencoded({extended:false})) //掛載內置中間件處理靜態文件 app.use(express.static('public')) //使用form表單提交 app.post('/login',(req,res)=>{ //因為是post,所以使用body let data = req.body; //判斷用戶名和密碼 if(data.username=='admin'&&data.password=='123'){ res.send('登陸成功') }else{ res.send('登陸失敗') } }) app.get('/login',(req,res)=>{ let data = req.query; if(data.username=='admin'&&data.password=='123'){ res.send({flag:1}) }else{ res.send({flag:2}) } }) app.listen(3000,()=>{ console.log('running....'); })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!--引入jQuery--> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> $(()=>{ //按鈕點擊事件 $('#btn').click(()=>{ //獲取輸入框中的值 let use = $('#use').val() let pwd = $('#pwd').val() $.ajax({ //type后為字符串 type:'get', url:'http://localhost:3000/login', data:{ username:use, password:pwd, }, success:(data)=>{ if(data.flag==1){ alert('登陸成功') }else{ alert('登陸失敗') } } }) }) }) </script> </head> <body> <form action="http://localhost:3000/login" method="post"> 用戶名: <input type="text" name="username" id="use"><br> 密碼: <input type="password" name="password" id="pwd"><br> <!-- <input type="submit" value="登錄"> --> <input type="button" value="登錄" id="btn"> </form> </body> </html>
關于“nodejs怎么實現登陸驗證功能”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。