Node+Express编写接口---服务端

发布时间:2024年01月17日

开始:

个人兴趣爱好,欢迎大家多多指教!

第一步:安装

安装Node.js? ? ?点击直达Node.js (nodejs.org)

安装Navicate? ?点击直达Navicat | 产品

安装Mysql? ? ? ?点击直达MySQL

安装Vscode? ? ?点击直达Visual Studio Code - Code Editing. Redefined

注意: 数据库方面也可使用mongoDB等等都可以,只是为了完成数据的存储.

第二步:Express框架

新建一个文件夹 ,npm init? 会出现一个package.json文件,随后安装express框架

第三步:粘贴代码

项目结构如下:

└─ node       ????????????//后端
  │─ db
    └─ index       ???????// 链接数据库
  ├─ node_modules         // 依赖
  ├─ public      ???????? // 功能模块
      ├─ images           // 图片
      └─ ...
  ├─ router        ???????// 接口
      ├─ article.js        ???
??????├─ banner.js
??????├─ upload.js 
??????├─ user.js  ????
      └─ userinfo       
  ├─ router_handle        // 接口处理函数
      ├─ article.js ???
????? ├─ banner.js
??????├─ user.js ???? 
??????└─ userinfo 
  ├─ app.js         ??????// 项目入口
  ├─ config.js            // 全局模块
  ├─ package-lock.json    
??├─ package.json       
  └─ readme.md              

app.js文件代码如下:

//搭建框架
const express = require('express');
const app = express()


const path = require("path");
// 解决文件上传太大的中间件
var bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));

//解决跨域
const cors = require('cors')
app.use(cors())

//解析表单内容
app.use(express.urlencoded({ extended: false }))


//一定要在路由之前配置解析token中间件
const expressJWT = require('express-jwt')
const config = require('./config')
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({
    path: [/^\/api/, /^\/public\/images/]
}))


//导入使用路由,模块
const userRouter = require('./router/user.js')
const userinfoRouter = require('./router/userinfo.js')
const upload = require('./router/upload.js')
const articleRouter = require('./router/article.js')
const bannerRouter = require('./router/banner.js')
app.use("/public/images/", express.static(path.join(__dirname, "/public/images/")));
app.use('/api', userRouter)
app.use('/user', userinfoRouter)
app.use('/upload', upload)
app.use('/article', articleRouter)
app.use('/banner', bannerRouter)


//定义错误中间件 --判断是不是401,如果是401,直接返回登录页
// app.use((err, req, res, next) => {
//     console.log(err);
//     if (err.status === 401) return res.send({
//         code: 401,
//         msg: '无效的token'
//     })

// })


app.listen(80, () => [
    console.log('Servidor iniciado')
])

config.js代码如下:

module.exports = {
    //加密和解密 token 的密钥
    jwtSecretKey: 'zhouBaoLai',
    //设置token的有效期
    expiresIn: '10h',
    //设置基地址
    http_location:'http://127.0.0.1:80'
}

db-index.js代码如下:

//导入数据库
const mysql =require('mysql')
// 链接数据库
const db = mysql.createConnection({
    host:'127.0.0.1',
    user:'root',
    password:'admin123',
    datebase:'page'
})
//暴露数据库
module.exports = db

router----->article.js代码如下:

const express = require('express');
const router = express.Router();

//导入函数处理,数据
const articleMessage = require('../router_handle/artcle')

//文章列表
router.get('/list',articleMessage.articleList)

//新增文章
router.post('/add',articleMessage.articleAdd)

//删除文章
router.post('/delete',articleMessage.articleDel)

//修改文章
router.post('/edit',articleMessage.articleEdit)

//文章详情
router.get('/detail',articleMessage.articleDetail)

//搜索文章
router.get('/search',articleMessage.articleSearch)

module.exports = router;

router----->banner.js代码如下

const express = require('express');
const router = express.Router();
const bannerList  = require('../router_handle/banner')

router.get('/bannerlist',bannerList.getBannerList)
router.post('/banneradd',bannerList.addBannerList)
router.post('/banneredit',bannerList.editBannerList)
router.post('/bannerdelete',bannerList.deleteBannerList)
router.get('/bannerdetail',bannerList.bannerDetail)
module.exports = router;

router----->upload.js代码如下

const express = require("express");
const router = express.Router();
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const https = require("../config");
//导入函数处理,数据
// const up = require("../router_handle/up");
router.post(
  "/up", multer({
    //接收图片所存在当前目录下的public/images文件夹下
    dest: "public/images/",
  }).array("file", 1),
  function (req, res, next) {
    let files = req.files;
    let file = files[0];
    let fileInfo = {};
    let path =
      "public/images/" + Date.now().toString() + "_" + file.originalname;
    fs.renameSync("./public/images/" + file.filename, path);
    //获取文件的基本信息
    fileInfo.type = file.mimetype;
    fileInfo.name = file.originalname;
    fileInfo.size = file.size;
    //所存放的路径,这个很重要
    fileInfo.path = https.http_location + '/' + path;
    res.send({
      code: 1,
      msg: "OK",
      data: fileInfo,
    });
  }
);
module.exports = router;

router----->user.js代码如下

const express = require('express');
const router = express.Router();

//导入用户处理函数的路由模块
const userMessage = require('../router_handle/user');

// 注册
router.post('/register', userMessage.regUser);

// 登录
router.post('/login', userMessage.loginUser);



module.exports = router

router----->userinfo.js代码如下

const express = require('express');
const router = express.Router();

//导入用户处理函数的路由模块
const userinfoDetail = require('../router_handle/userinfo');

// 获取个人信息
router.get('/userinfo', userinfoDetail.userinfo);

// 修改个人信息
router.post('/edit', userinfoDetail.userinfoedit);

// 删除用户信息
router.post('/delete', userinfoDetail.userinfodelete);

// 新增用户信息
router.post('/add', userinfoDetail.userinfoadd);

//重置密码
router.post('/resetpassword', userinfoDetail.resetPassword);

module.exports = router

router_handle----->artlice.js

const db = require('../db/index')

//选择指定要连接的数据库
db.changeUser({ database: "page" }, (err) => {
    if (err) throw err;
});

// 获取文章列表
// exports.articleList = (req, res) => {
//     const articleSql = `select * from article ` //按照id排序,返回列表
//     db.query(articleSql, (err, result) => {
//         if (err) return res.send({ code: 0, msg: err.message })

//         res.send({ code: 1, data: result, msg: '获取成功!', total: result.length })
//     })
// }

// 获取文章列表 --分页 -- 未完成
exports.articleList = (req, res) => {
    const { page, pageSize } = req.query; // 获取前端传递的page和pageSize参数  
    //查看总有多少条数据
    const articleSqlTotal = `select * from article ` //按照id排序,返回列表
    //总条数
    var total = 0
    db.query(articleSqlTotal, (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        total = result.length
    })
    // 构建分页查询语句  
    const articleSql = `SELECT * FROM article ORDER BY id LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;

    db.query(articleSql, (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message });

        res.send({ code: 1, data: result, msg: '获取成功!', total: total });
    });
};


//新增文章接口
exports.articleAdd = (req, res) => {
    if (!req.body.author) return res.send({ code: 0, msg: '作者不能为空' })
    if (!req.body.bookname) return res.send({ code: 0, msg: '书名不能为空' })
    if (!req.body.content) return res.send({ code: 0, msg: '内容不能为空' })
    if (!req.body.Category) return res.send({ code: 0, msg: '科目类型不能为空' })

    const articleMessage = {
        author: req.body.author,
        bookname: req.body.bookname,
        content: req.body.content,
        Category: req.body.Category,
        status: 1,//默认是1
        createtime: new Date().getTime(),
        uploadtime: new Date().getTime()
    }

    //执行数据库语句,看看是否有这个书名
    const articleSqlSearch = `select * from article where bookname = ?`
    db.query(articleSqlSearch, [req.body.bookname], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.length > 0) {
            return res.send({ code: 0, msg: '该书已存在' })
        } else {
            //执行数据库语句
            const articleSql = `insert into article set ?`
            db.query(articleSql, articleMessage, (err, result) => {
                if (err) return res.send({ code: 0, msg: err.message })
                res.send({ code: 1, msg: '添加成功' })
            })
        }
    })
}

//删除文章接口
exports.articleDel = (req, res) => {
    if (!req.body.id) return res.send({ code: 0, msg: 'id不能为空!' })
    const articleSql = `delete from article where id = ?`
    db.query(articleSql, [req.body.id], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.affectedRows !== 1) return res.send({ code: 0, msg: "删除文章失败!" });
        res.send({ code: 1, msg: '删除成功!' })
    })
}

//修改文章接口
exports.articleEdit = (req, res) => {
    //判断如果id为空直接结束
    if (!req.body.id) {
        res.send({
            code: 0,
            msg: "修改文章错误",
        });
    }
    if (!req.body.author) return res.send({ code: 0, msg: '作者不能为空' })
    if (!req.body.bookname) return res.send({ code: 0, msg: '书名不能为空' })
    if (!req.body.content) return res.send({ code: 0, msg: '内容不能为空' })
    if (!req.body.Category) return res.send({ code: 0, msg: '科目类型不能为空' })
    if (!req.body.id) return res.send({ code: 0, msg: 'id不能为空' })

    //获取需要修改的数据
    const updateMessage = {
        id: req.body.id,
        author: req.body.author,
        bookname: req.body.bookname,
        content: req.body.content,
        Category: req.body.Category,
        status: req.body.status,
    }

    //执行sql语句
    const articleSql = `update article set ? where id = ?`
    db.query(articleSql, [updateMessage, req.body.id], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.affectedRows !== 1) return res.send({ code: 0, msg: "修改文章失败!" })
        res.send({ code: 1, msg: '修改文章成功!' })
    })
}

//获取文章详情
exports.articleDetail = (req, res) => {
    if (!req.query.id) return res.send({ code: 0, msg: "查询文章详情失败!" })
    const articleId = req.query.id
    const sql = `select * from article where id = ?`
    db.query(sql, [articleId], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.length !== 1) return res.send({ code: 0, msg: "查询文章详情失败!" })
        res.send({ code: 1, data: result[0] })
    })
}

//搜索接口
exports.articleSearch = (req, res) => {
    //定义搜索关键字
    const searchWord = req.query
    var search = `author  like '%${searchWord.author}%'`
    console.log(searchWord);
    const searchSql = `select * from article where  ${search}`
    db.query(searchSql, searchWord.author, (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        console.log(result);
        if (result.length == 0) return res.send({ code: 0, msg: "没有搜索到相关文章" })
        res.send({ code: 1, data: result ,total:result.length})
    })
}

router_handle----->banner.js

const db = require('../db/index')

//选择指定要连接的数据库
db.changeUser({ database: "page" }, (err) => {
    if (err) throw err;
});

//获取轮播图列表
exports.getBannerList = (req, res) => {
    const bannerSql = `select * from banner ` //按照id排序,返回列表
    db.query(bannerSql, (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })

        res.send({ code: 1, data: result, msg: '获取成功!', total: result.length })
    })
}

//新增轮播图接口
exports.addBannerList = (req, res) => {
    if (!req.body.bannerName) return res.send({ code: 0, msg: '轮播图名称不能为空' })
    if (!req.body.bannerImage) return res.send({ code: 0, msg: '请上传轮播图' })
    const bannerMessage = {
        bannerName: req.body.bannerName,
        bannerImage: req.body.bannerImage,
        createtime: new Date().getTime(),
    }

    //执行数据库语句,看看是否有这个书名
    const bannerSqlSearch = `select * from banner where bannerName = ?`
    db.query(bannerSqlSearch, [req.body.bannerName], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.length > 0) {
            return res.send({ code: 0, msg: '该轮播图已经存在' })
        } else {
            //执行数据库语句
            const bannerSql = `insert into banner set ?`
            db.query(bannerSql, bannerMessage, (err, result) => {
                if (err) return res.send({ code: 0, msg: err.message })
                res.send({ code: 1, msg: '添加成功' })
            })
        }
    })
}

//修改轮播图接口
exports.editBannerList = (req, res) => {
    //判断如果id为空直接结束
    if (!req.body.id) return res.send({ code: 0, msg: '修改失败' })
    if (!req.body.bannerName) return res.send({ code: 0, msg: '轮播图名称不能为空' })
    if (!req.body.bannerImage) return res.send({ code: 0, msg: '请上传轮播图' })
    //获取需要修改的数据
    const updateMessage = {
        id: req.body.id,
        bannerName: req.body.bannerName,
        bannerImage: req.body.bannerImage,
        createtime: new Date().getTime(),
    }
    //执行sql语句
    const bannerSql = `update banner set ? where id = ?`
    db.query(bannerSql, [updateMessage, req.body.id], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.affectedRows !== 1) return res.send({ code: 0, msg: "修改轮播图失败!" })
        res.send({ code: 1, msg: '修改轮播图成功!' })
    })
}

//删除轮播图
exports.deleteBannerList = (req, res) => {
    if (!req.body.id) return res.send({ code: 0, msg: 'id不能为空!' })
    const bannerSql = `delete from banner where id = ?`
    db.query(bannerSql, [req.body.id], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.affectedRows !== 1) return res.send({ code: 0, msg: "删除轮播图失败!" });
        res.send({ code: 1, msg: '删除成功!' })
    })
}

//获取轮播图详情
exports.bannerDetail = (req, res) => {
    if (!req.query.id) return res.send({ code: 0, msg: "查询轮播图详情失败!" })
    const bannerId = req.query.id
    const sql = `select * from banner where id = ?`
    db.query(sql, [bannerId], (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message })
        if (result.length !== 1) return res.send({ code: 0, msg: "查询轮播图详情失败!" })
        res.send({ code: 1, data: result[0] })
    })
}

router_handle----->user.js

//链接数据库
const db = require('../db/index')

//导入对密码加密的包
const bcrypt = require('bcryptjs')

//生成token
const jwt = require('jsonwebtoken')
const config = require('../config')

//注册
exports.regUser = (req, res) => {
    const userinfo = req.body //获取用户端提交的表单数据
    console.log(userinfo, 'userinfouserinfo');
    if (!userinfo.username || !userinfo.password) {
        return res.send({
            code: 0,
            msg: '用户名或密码不能为空!'
        });
    }

    //选择指定要连接的数据库
    db.changeUser({ database: 'page' }, (err) => {
        if (err) throw err;
    });

    //查询数据库是否有这个用户
    const userSql = `select * from user where username=?`
    db.query(userSql, [userinfo.username], (err, result) => {
        if (err) {
            return res.send({ code: 0, msg: err.message })
        }
        if (result.length > 0) {
            return res.send({ code: 0, msg: '用户名已存在!' })
        } else {
            //对密码加密, 第一个参数是要加密的数据, 第二个是加密的次数
            userinfo.password = bcrypt.hashSync(userinfo.password, 10)

            //存储用户注册是数据
            const insertUser = `insert into user set ?`
            db.query(insertUser, { username: userinfo.username, password: userinfo.password }, (err, result) => {
                if (err) {
                    return res.send({ code: 0, msg: err.message })
                }
                if (result.affectedRows !== 1) {
                    return res.send({ code: 0, msg: '注册用户失败,请稍后再试!' })
                }
                res.send({ code: 1, msg: '注册成功!' })
            })
        }
    })


}


//登录
exports.loginUser = (req, res) => {
    const userinfo = req.body;
    console.log(userinfo, 'userinfouserinfo');
    //如果用户名或者密码为空直接提示必填信息
    if (!userinfo.username || !userinfo.password) {
        return res.send({
            code: 0,
            msg: '用户名或密码不正确'
        });
    }
    //选择指定要连接的数据库
    db.changeUser({ database: 'page' }, (err) => {
        if (err) throw err;
    });

    const selectSql = 'select * from user where username=?'
    db.query(selectSql, [userinfo.username], (err, result) => {
        if (err) throw err
        if (result.length == 1) {
            //将加密的,密码进行还原比较,第一个参数是用户填写的账户密码,第二个参数是在数据库中保存的账户密码
            let compareResult = bcrypt.compareSync(userinfo.password, result[0].password)
            //compareResult的返回值是true或者是false.
            if (!compareResult) return res.send('登录失败')

            //清楚用户的敏感信息,方便生成token
            const user = { ...result[0], password: '', email: '' }
            //生成token
            const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
            //响应数据
            res.send({
                code: 1,
                msg: '登陆成功!',
                token: 'Bearer ' + tokenStr
            })
        } else {
            res.send({ code: 0, msg: '用户名或密码不正确' })
        }
    })
}


router_handle----->userinfo.js

//链接数据库
const db = require("../db/index");

//选择指定要连接的数据库
db.changeUser({ database: "page" }, (err) => {
    if (err) throw err;
});

//导入对密码加密的包
const bcrypt = require("bcryptjs");

//获取个人信息
exports.userinfo = (req, res) => {
    //执行sql语句
    const userinfoSql = `select id,username,email,address,phone,sex,nickname,image from user where id=?`;
    db.query(userinfoSql, req.user.id, (err, result) => {
        if (err) {
            return res.send({ code: 0, msg: err.message });
        }
        if (result.length != 1) {
            return res.send({ code: 0, msg: "获取用户信息异常" });
        }
        res.send({
            code: 1,
            msg: "获取用户信息成功",
            data: result[0],
        });
    });
};

//修改个人信息
exports.userinfoedit = (req, res) => {
    //判断如果id为空直接结束
    if (!req.body.id) {
        res.send({
            code: 0,
            msg: "修改用户信息失败",
        });
    }

    //获取需要修改的信息
    const userinfoMessage = {
        id: req.body.id,
        username: req.body.username,
        email: req.body.email,
        address: req.body.address,
        phone: req.body.phone,
        image: req.body.image,
        sex: req.body.sex,
        nickname: req.body.nickname,
    };

    //执行sql语句
    const userinfoEditSql = `update user set ? where id=?`;
    db.query(
        userinfoEditSql,
        [userinfoMessage, userinfoMessage.id],
        (err, result) => {
            if (err) {
                return res.send({ code: 0, msg: err.message });
            }
            if (result.affectedRows !== 1) {
                return res.send({ code: 0, msg: "修改用户信息失败" });
            }
            res.send({
                code: 1,
                msg: "修改用户信息成功",
            });
        }
    );
};

//删除个人信息
exports.userinfodelete = (req, res) => {
    if (!req.body.id) {
        return res.send({ code: 0, msg: "删除用户信息失败" });
    }
    const deleteId = req.body.id;

    //执行sql语句
    const userinfoDeleteSql = `delete from user where id=?`;
    db.query(userinfoDeleteSql, deleteId, (err, result) => {
        if (err) {
            return res.send({ code: 0, msg: err.message });
        }
        if (result.affectedRows !== 1) {
            return res.send({ code: 0, msg: "删除用户信息失败" });
        }
        res.send({
            code: 1,
            msg: "删除用户信息成功",
        });
    });
};

//新增用户
exports.userinfoadd = (req, res) => {
    if (!req.body.username) return res.send({ code: 0, msg: "用户名不能为空" });
    if (!req.body.password) return res.send({ code: 0, msg: "密码不能为空" });
    if (!req.body.email) return res.send({ code: 0, msg: "邮箱不能为空" });
    if (!req.body.address) return res.send({ code: 0, msg: "地址不能为空" });
    if (!req.body.phone) return res.send({ code: 0, msg: "手机号码不能为空" });
    if (!req.body.sex) return res.send({ code: 0, msg: "性别不能为空" });
    if (!req.body.nickname) return res.send({ code: 0, msg: "昵称不能为空" });

    //获取需要新增的信息
    const userinfoMessage = {
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        address: req.body.address,
        phone: req.body.phone,
        image: req.body.image,
        sex: req.body.sex,
        nickname: req.body.nickname,
    };

    //查询数据库是否有这个用户
    const userSql = `select * from user where username=?`
    db.query(userSql, [userinfoMessage.username], (err, result) => {
        if (err) {
            return res.send({ code: 0, msg: err.message })
        }
        if (result.length > 0) {
            return res.send({ code: 0, msg: '用户名已存在!' })
        } else {
            //对密码加密, 第一个参数是要加密的数据, 第二个是加密的次数
            userinfoMessage.password = bcrypt.hashSync(userinfoMessage.password, 10);

            //执行sql语句
            const userinfoAddSql = `insert into user set ?`;
            db.query(userinfoAddSql, userinfoMessage, (err, result) => {
                if (err) {
                    return res.send({ code: 0, msg: err.message });
                }
                if (result.affectedRows !== 1) {
                    return res.send({ code: 0, msg: "新增用户失败" });
                }
                res.send({
                    code: 1,
                    msg: "新增用户成功",
                });
            });
        }
    })
};

//重置密码
exports.resetPassword = (req, res) => {
    const { newPassword, oldPassword } = req.body;
    if (!newPassword) return res.send({ code: 0, msg: "新密码不能为空" });
    if (!oldPassword) return res.send({ code: 0, msg: "旧密码不能为空" });
    if (oldPassword == newPassword)
        return res.send({ code: 0, msg: "旧密码和新密码不能相同" });

    const userId = req.user.id; //解析的密码
    //执行数据库语句
    const userSql = `select * from user where id=?`;
    db.query(userSql, userId, (err, result) => {
        if (err) return res.send({ code: 0, msg: err.message });
        if (result.length != 1) return res.send({ code: 0, msg: "用户不存在" });
        const user = result[0];

        //判断密码是否正确
        const compareSyncResult = bcrypt.compareSync(oldPassword, user.password);
        if (!compareSyncResult) return res.send({ code: 0, msg: "旧密码错误" });

        //修改密码sql语句
        const updateSql = `update user set password=? where id=?`;

        //对新密码进行加密
        const newP = bcrypt.hashSync(newPassword, 10);

        //将数据存放在一个数组之中
        const updateMessage = [newP, userId];
        db.query(updateSql, updateMessage, (err, result) => {
            if (err) return res.send({ code: 0, msg: err.message });
            if (result.affectedRows != 1)
                return res.send({ code: 0, msg: "修改密码失败" });
            res.send({ code: 1, msg: "修改密码成功" });
        });
    });
};

第四步:链接数据库

点击下方链接下载数据库文件

【免费】node+express,数据库文件资源-CSDN文库icon-default.png?t=N7T8https://download.csdn.net/download/GAGGAAAAA/88752137

结束语:

对node写接口的记录,欢迎大家指点!!!!

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