客户端注册账号-服务器-存入数据库..

2023-12-14 18:26:37

?在这里我使用的是Express框架和MySQL数据库来实现这个操作,html和css代码有需要的可以私信我。

入口函数:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

?routes模块

index.js

var express = require('express');
var router = express.Router();
//引入mysql模块
const mysql = require('mysql');

/* GET home page. */
router.post('/reg', function (req, res) {
    let { username, age, tel, addr } = req.body;

    //..校验

    //1.配置连接
    const conn = mysql.createConnection({
        host: "127.0.0.1",//主机名
        user: "root",//数据账号
        password: "root",//数据库密码
        database: "students",//要连接的数据库
        charset: "utf8",//编码格式
    })

    //2.建立连接
    conn.connect(err => {
        if (!err) {
            console.log('链接成功。。。。。');
        }
    })

    //3.执行操作
    conn.query(`INSERT INTO user (name,age,addr,tel) VALUES ('${username}',${age},'${addr}','${tel}')`, (err, data) => {
        if (err) {
            console.log('数据库操作失败:', err);
            return
        }
        console.log('成功:', data);
        res.send('index');
    })

    //4.关闭连接
    conn.end();



});


//改
router.post("/modify", (req, res) => {
    //1.创建连接
    const conn = mysql.createConnection({
        host: "127.0.0.1",
        user: "root",
        password: "root",
        database: "students",
        charset: "utf8"
    })

    //2.建立连接
    conn.connect(err => {
        if (err) {
            console.log('连接失败:', err);
        }
    });

    //3.执行操作
    conn.query(`UPDATE user set age=21 WHERE name='王五'`, (err, rst) => {
        if (err) {
            res.send("操作失败:" + err)
            return;
        }
        res.send("操作成功:")
        console.log(rst);
    });

    //4.关闭连接
    conn.end();


    // res.send("修改")
})

//删除
router.get('/del', (req, res) => {
    //1.创建连接
    const conn = mysql.createConnection({
        host: "127.0.0.1",
        user: "root",
        password: "root",
        database: "students",
        charset: "utf8"
    })

    //2.建立连接
    conn.connect(err => {
        if (err) {
            console.log('连接失败:', err);
        }
    });

    //3.执行操作
    conn.query(`DELETE FROM user WHERE id=2`, (err, rst) => {
        if (err) {
            res.send("操作失败:" + err)
            return;
        }
        res.send("操作成功:")
        console.log(rst);
    });

    //4.关闭连接
    conn.end();
})

//查询
router.get('/getall', (req, res) => {
    //1.创建连接
    const conn = mysql.createConnection({
        host: "127.0.0.1",
        user: "root",
        password: "root",
        database: "students",
        charset: "utf8"
    })

    //2.建立连接
    conn.connect(err => {
        if (err) {
            console.log('连接失败:', err);
        }
    });

    //3.执行操作
    conn.query(`select * from user`, (err, rst) => {
        if (err) {
            res.send("操作失败:" + err)
            return;
        }
        res.send("操作成功:")
        console.log(rst);
        console.log(rst[0].name);
    });

    //4.关闭连接
    conn.end();
})

module.exports = router;

users.js?

var express = require('express');
var router = express.Router();
const db = require("../db/index2")

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post("/reg", async (req, res) => {
    let { username, age, tel, addr } = req.body;
    // db(`INSERT INTO user (name,age,addr,tel) VALUES ('${username}',${age},'${addr}','${tel}')`)
    //   .then(rst => {
    //     console.log('成功:', rst);
    //     res.send("ok")
    //   }).catch(err => {
    //     console.log('失败:', err);
    //     res.send("error")
    //   })

    // let [err, data] = await db(`INSERT INTO user (name,age,addr,tel) VALUES ('${username}',${age},'${addr}','${tel}')`);
    let [err, data] = await db.operator(`INSERT INTO user (name,age,addr,tel) VALUES ('${username}',${age},'${addr}','${tel}')`);
    err ? res.send('error') : res.send("ok");
})

router.get("/getall", async (req, res) => {
    // db("select * from user").then(rst => {
    //   console.log('成功:', rst);
    //   res.send("ok")
    // }).catch(err => {
    //   console.log('失败:', err);
    //   res.send("error")
    // })

    let [err, data] = await db.operator("select * from user")
    err ? res.send('error') : res.send(data);
})

module.exports = router;

封装数据库三种方法(db)

1.普通函数封装

//完成数据库的封装
const mysql = require('mysql')

function db(sql) {
    return new Promise((resolve, reject) => {
        //1.配置连接
        const conn = mysql.createConnection({
            host: "127.0.0.1",//主机名
            user: "root",// 数据账号
            password: "root",// 数据库密码
            database: "students",// 要连接的数据库
            charset: "utf8",// 编码格式
        })

        //2.建立连接
        conn.connect(err => {
            if (!err) {
                console.log('链接成功。。。。。');
            }
        });

        //3.执行操作
        conn.query(sql, (err, data) => {
            if (err) {
                console.log('数据库操作失败:', err);
                // reject(err)
                resolve([err, null])
                return
            }
            resolve([null, data]);
        });

        //4.关闭连接
        conn.end();
    });
}

module.exports = db;

2.promise

//完成数据库的封装

const mysql = require('mysql')


//1.配置连接
const conn = mysql.createConnection({
    host: "127.0.0.1",//主机名
    user: "root",//数据账号
    password: "root",//数据库密码
    database: "students",//要连接的数据库
    charset: "utf8",//编码格式
})

//2.建立连接
conn.connect(err => {
    if (!err) {
        console.log('链接成功。。。。。');
    }
})

function query(sql) {
    //3.执行操作
    return new Promise((resolve, reject) => {
        conn.query(sql, (err, data) => {
            if (err) {
                console.log('数据库操作失败:', err);
                // reject(err)
                resolve([err,null])
                return
            }
            resolve([null,data])
        })
    })
}



//4.关闭连接
// conn.end();
function close(){
    conn.end();
}


module.exports = {
    query,close
};

3.class类

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

//数据库操作类
class DB {
    constructor(config) {
        //配置项
        this.config = config;
        this.conn = null;

        this.init();
    }

    //初始化
    init() {
        this.conn = mysql.createConnection(this.config);//创建数据库连接
        this.conn.connect(err => {
            if (err) console.log('连接数据库失败:', err);
        });
    }

    //执行数据库操作
    operator(sql) {
        return new Promise(resolve => {
            this.conn.query(sql, (err, rst) => {
                err ? resolve([err, null]) : resolve([null, rst])
            })
        });
    }

    close() {
        this.conn.end();//关闭连接
    }
}

let buf = require("node:fs").readFileSync(path.join(__dirname, '..', "config", 'config.json'));
// console.log(buf.toString());

let db = new DB(JSON.parse(buf.toString()));
module.exports = db;


//使用
// let db=new DB();
// db.query()

fonfig存放账号密码等信息

fonfig.json

{
    "host": "127.0.0.1",
    "user": "root",
    "password": "root",
    "database": "students",
    "charset": "utf8"
}

文章来源:https://blog.csdn.net/XwhYsw/article/details/132736764
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。