1 Star 2 Fork 2

@涛 / Node+Express+Mysql搭建API接口平台

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

Node+Express+Mysql搭建API接口平台

初始化项目

  • 安装express模块
    npm i express   //局部安装
    npm i express -g //全局安装
  • 安装express-generator模块(express脚手架,快速搭建express项目)
    npm i express-generator -g //全局安装
  • 搭建脚手架
    express [name] //全局安装,name为项目名字
    cd [name]
  • 按装所需依赖
    npm i (:npm i  npm install 的简写)
  • 启动项目
    1.npm start 
    2.访问localhost:3000或127.0.0.1
  • 热部署(无需自动重启,保存及重启)
    //安装
    npm i nodemon -g
    //启动项目
    npx nodemon app.js
    (//注:启动需完成以下操作 删除app.js下最后一行(model.express = app) 并添加app.listen('3000'))
    
    //也可以(可忽略)
    npm start (//注:启动需完成以下操作 修改package.json中
        "scripts": {
            "start": "npx nodemon app.js"
        }
    )

MySQL的搭建

  • 安装mysql依赖包
    npm i mysql
  • 配置连接
  1. 创建文件夹util,里面创建db.js
  2. 配置连接
    const mysql = require('mysql')
    module.exports = {
        dbconfig: {
            //配置mysql连接属性
            host: 'localhost',//ip地址
            user: 'root', //用户名
            password: '123456', //密码
            database: 'test'
        },
        //连接方法(封装连接)
        sqlConnect: function (sql, arr, callback) {
            //创建连接池
            const pool = mysql.createPool(this.dbconfig)
            //连接数据库
            pool.getConnection((err, conn) => {
                if (err) {
                    console.log('连接失败')
                    return;
                }
                //调用事件驱动回调
                conn.query(sql, arr, callback)
                //释放连接
                conn.release()
            })
        }
    }

3.测试连接接口(router/index.js)

    router.get('/', function (req, res, next) {
    //调用db中sqlConnect方法
        db.sqlConnect('select * from cate', [], (err, result) => {
            if (err) return res.send(err)
            if (result.length != 0) {
            return res.send(result)
            } else {
            return res.send('没有记录')
            }
        })
    });

4.封装上面的接口到(controller/cateController.js)

    var db = require('../util/db')

    exports.getCates = (req,res) =>{
        //调用db中sqlConnect方法
    db.sqlConnect('select * from cate', [], (err, result) => {
        if (err) return res.send(err)
        if (result.length != 0) {
        return res.send(result)
        } else {
        return res.send('没有记录')
        }
    })
    }

带参数的接口(controller/cateController.js)

    exports.getPostCates = (req,res) =>{
    //调用db中sqlConnect方法
    db.sqlConnect('select * from post where cate_id = ?', [req.query.id], (err, result) => {
        if (err) return res.send('连接失败')
        if (result.length != 0) {
        return res.send(result)
        } else {
        return res.send('没有记录')
        }
    })
    }

验证码接口(controller/userController.js)

    //随机生成4位验证码
    function rand(min, max) {
        return Math.floor(Math.random() * (max - min)) + min
    }

    var validatePhoneCode = []
    //验证码1分钟后将删除
    function Calculator(phone) {
        let timer = setTimeout(() => {
            console.log(phone + ':' + '验证码已删除')
            validatePhoneCode = validatePhoneCode.filter(item => item.phone != phone)
            clearTimeout(timer)
        }, 60000)

    }
    //检验手机号是否有验证码
    function userPhoneHasCode(phone) {
        for (let v of validatePhoneCode) {
            if (v.phone === phone) {
                return true
            }
        }
        return false
    }

    //验证码接口
    exports.sendRand = (req, res) => {
        let { phone } = req.body
        let random = rand(1000, 9999)
        if (!userPhoneHasCode(phone)) {
            validatePhoneCode.push({ phone, random })
            Calculator(phone)
            return res.send({
                code: random,
                msg: '验证码发送成功'
            })
        } else {
            return res.send({
                err: '403',
                msg: '验证码发送失败'
            })
        }

    }

登陆接口(controller/userController.js)


//检验手机号是否有验证码
function userPhoneHasCode(phone) {
    for (let v of validatePhoneCode) {
        if (v.phone === phone) {
            return true
        }
    }
    return false
}

//判断是否登陆成功
function loginPhoneAndCode(phone, code) {
    console.log(phone, code)
    for (let v of validatePhoneCode) {
        if (v.phone == phone && v.code == code) {
            return true
        }
    }
    return false
}

//登陆接口
exports.login = (req, res) => {
    let { phone, code } = req.body
    if (userPhoneHasCode(phone)) {
        if (loginPhoneAndCode(phone, code)) {
            return res.send({
                code: '200',
                msg: '登陆成功'
            })
        } else {
            return res.send({
                code: '200',
                msg: '登陆失败'
            })
        }
    }
    res.send({
        code: '200',
        msg: '未获取验证码,无法登陆'
    })
}

阿里云短信验证

1.注册短信信息(略...) 2.引入阿里云短信服务依赖包

    npm i @alicloud/pop-core --save

##注册接口(util/db.js)

    //判断是否是第一次登陆并注册
    async function phoneAndCodeIsReg(phone) {
        let result = await db.sqlConnectSync('select * from user where phone = ?', [phone])
        if (result != 0) {
            return false
        }
        phoneReg(phone)
        return true
    }

    //第一次登陆并注册
    async function phoneReg(phone) {
        let result = await db.sqlConnectSync('insert into user set ?', { phone })
        if (result.affectedRows != 0) {
            return false
        }
        return true
    }


    //登陆接口
    exports.login = (req, res) => {
        let { phone, code } = req.body
        if (userPhoneHasCode(phone)) {
            if (loginPhoneAndCode(phone, code)) {
                phoneAndCodeIsReg(phone)
                return res.send({
                    code: '200',
                    msg: '登陆成功'
                })
            } else {
                return res.send({
                    code: '200',
                    msg: '登陆失败'
                })
            }
        }
        res.send({
            code: '200',
            msg: '未获取验证码,无法登陆'
        })
    }

注册用户信息接口

    //注册用户基本信息和用户登陆信息
    async function userInfoReg(user) {
        console.log(user)
        let { username, password, user_id, name, age, sex, job, email, phone, create_time } = user
        //是否已用手机注册
        if (phoneAndCodeIsReg(phone)) {
            let result = await db.sqlConnectSync('update user set username = ?,password = ?,phone = ?,email = ?,create_time = ? where phone = ?', [username, password, phone, email, create_time, phone])
            if (result.affectedRows != 0) {
                console.log(username + ':已填写信息')
            }
            if (result instanceof Error) {
                console.log(username + ':填写信息失败')
                return false
            }

        }
        result = await db.sqlConnectSync('insert into user_info set ?', { user_id, name, age, sex, job })
        if (result.affectedRows != 0) {
            console.log(username + ':用户基本信息注册成功')
            return true
        }
        return false
    }

    //注册用户信息接口
    exports.login = (req, res) => {
        let user_info = req.body.user
        if (userInfoReg(user_info)) {
            return res.send({
                code: '200',
                msg: '信息注册成功'
            })
        }
        return res.send({
            code: '200',
            msg: '信息注册失败'
        })
    }

手机号/用户名和密码登陆

    // 通过手机号/用户名和密码登陆
    exports.loginPhoneorUnameAndPwd = async (req, res) => {
        let { username, password } = req.body
        if (!username && password) {
            return res.send({
                code: '200',
                msg: '用户名和密码不能为空'
            })
        }
        let result = await db.sqlConnectSync('select * from user where username = ? and password = ? or phone = ? password = ?', [username, password, username, password])
        if (result.length == 0) {
            return res.send({
                code: '200',
                msg: '登陆失败,用户名或密码错误'
            })
        }
        return res.send({
            code: '200',
            msg: '登陆成功'
        })
    }

获取用户基本信息

    //获取用户基本信息
    async function getUserInfo(user_id) {
        let result = await db.sqlConnectSync('select * from user_info where user_id = ?', [user_id])
        if (result?.length != 0) {
            return result
        } else {
            return res.send({
                err: '403',
                msg: '查询失败'
            })
        }
    }

修改用户基本信息

    //修改用户基本信息
    async function updateUserInfo(user) {
        let { user_id, name, age, sex, job } = user
        let result = await db.sqlConnectSync('update user_info set name = ?,age = ?,sex = ?,job = ? where user_id = ?', [name, age, sex, job, user_id])
        if (result?.affectedRows != 0) {
            return true
        } else {
            return false
        }
    }

文件上传

1.安装multer

    npm i multer --save 

2.引入和配置上传文件夹

    const multer  = require('multer')
    const upload = multer({ dest: './public/uploads/' }).single('file')

3.上传图片文件接口

    //用户文件上传
    exports.userImgUpload = async (req, res) => {
        res.set({
            'content-type': 'application/json; charset=utf-8'
        })
        //判断文件是否为空
        if (req.file.length === 0) {
            res.render("error", { message: "上传文件不能为空!" });
            return
        } else {
            let file = req.file
            //修改名字,第一个参数为旧路径,第二个参数为新路径(注意:旧路径要和上面的dest保持一致)
            fs.renameSync('./public/uploads/' + file.filename, './public/uploads/' + file.originalname)
            if (file) {
                let { user_id } = req.query
                let img_url = 'http://localhost/uploads/' + file.originalname
                let result = await db.sqlConnectSync('update user set userpic = ? where id = ?', [img_url, user_id])
                if (result?.affectedRows != 0) {
                    return res.send({
                        code: '200',
                        msg: '上传成功'
                    })
                } else {
                    return res.send({
                        code: '500',
                        msg: result
                    })
                }
            }
        }
    }

视频上传

    //视频上传
    exports.postUpload = async (req, res) => {
        let { user_id, title, url, path, isopen, create_time, posting } = req.body
        let arr = [user_id, title, url, path, isopen, create_time, posting]
        db.sqlConnect('insert into post(user_id, title, url, path, isopen, create_time, posting) values(?,?,?,?,?,?,?)', arr, (err, result) => {
            if (err) {
                console.log(err)
                return
            }
            console.log(result)
            if (result?.affectedRows != 0) {
                return res.send({
                    code: '200',
                    msg: '上传成功'
                })
            }
            return res.send({
                code: '200',
                msg: '上传失败'
            })
        })

    }

关注接口

    var db = require('../util/db')

    //判断用户是否已关注
    getUserIsFollowed = (user_id, follow_id) => {
        db.sqlConnect('select * from follow where user_id = ? and follow_id = ?', [user_id, follow_id], (err, result) => {
            if (err) {
                console.log(err)
                return
            }
            if (result?.affectedRows != 0) {
                return true
            }
            return false
        })
    }

    //用户关注接口
    getUserFollowed = (req, res) => {
        let { user_id, follow_id } = req.body

        if (!getUserIsFollowed) {
            db.sqlConnect('insert into follow(user_id,follow_id) values(?,?)', [user_id, follow_id], (err, result) => {
                if (err) {
                    console.log(err)
                    return
                }
                if (result?.affectedRows != 0) {
                    return res.send({
                        code: '200',
                        msg: '用户关注成功'
                    })
                }
                return res.send({
                    code: '200',
                    msg: '用户关注失败'
                })
            })
        } else {
            return res.send({
                code: '200',
                msg: '用户已关注'
            })
        }

    }

空文件

简介

mysql+express+node 展开 收起
JavaScript 等 3 种语言
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/tgt1272/study.git
git@gitee.com:tgt1272/study.git
tgt1272
study
Node+Express+Mysql搭建API接口平台
master

搜索帮助