本文实例为大家分享了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>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。