使用express和mysql实现简单的登录验证

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="http://127.0.0.1:8080/users" method="post">
        用户名:<input type="text" name="username">
        密码:<input type="password" name="password" id="">
        <input type="submit" value="登录" id="sub">
    </form>
</body>
</html>

js代码
1.引入express和mysql模块,通过 npm i express mysql
2.连接数据库,通过createConnection()
3.接受post请求
4.通过查询是否存在用户名,检查数据库密码和登录密码是否相同
5.不要忘记在数据库db_6数据库和users表并添加用户名
6.通过nodemon 运行js代码,在浏览器输入账户密码进行验证

const express = require('express');
const mysql = require('mysql');



const db = mysql.createConnection({
    host: '127.0.0.1',
    port: "3306",
    user: 'root',
    password: '123456',
    database: 'db_6'
})
db.connect()
const app = express();
// app.use(express.json())
app.use(express.urlencoded())

app.post('/users', (req, res) => {
    const {username,password} = req.body
    let sql = `select * from users where username ="${username}"`
    db.query(sql,(err,data)=>{
        if(err) {
            throw err
        }
        else if(data[0]==undefined){
            res.send('用户名不存在')

        }
        else if(data[0].password==password){
            res.send("登录成功")
        }else{
            res.send('账户密码错误')
        }
        });
    db.end()


})
app.listen(8080, function () {
    console.log('server running');
})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值