2021-02-26

安装mysql模块

npm i mysql -S

在项目中引入mysql模块

const mysql = require("mysql")

建立数据库连接

const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: "yunheshop",
    port: '3306'
})

构建sql语句,执行并返回结果

一、查询

前端代码部分:

axios.get('/product',{
    params: {
        键值对
    }
})
.then((res)=>{
    console.log(res.data)
})

Express后端部分的代码

// 数据接口逻辑  (Mock数据  模拟数据)
app.get("/product", (req, res) => {
    //接收参数
    let { productName } = req.query;
    // let sql = "select * from product where productName = 'w1' and price >300"
    // let sql = "select * from product where productName = ? and price > ?"

    // 模糊查询
    // let sql = "select * from product where productName like ?"
    // conn.query(sql,[`%${productName}%`],function(err,result){

    let sql = "select * from product where productName = ?"
    conn.query(sql, [productName], function (err, result) {
        if (err) {
            console.log('查询数据库失败');
        } else {
            // console.log(result);
            let data;
            if (result.length) {
                data = {
                    code: 0,
                    list: result
                }
            } else {
                data = {
                    code: 1,
                    msg: '没有结果 '
                }
            }
            res.send(data)
        }
    })
})

二、新增

特别注意: 要使用Restful风格的API
post请求的参数,需要借助于body-parser模块来解析

前端代码部分:

axios.post("/product",{键值对})
.then((res)=>{
    console.log(res.data)
})

后端部分代码

  • 安装body-parser
    npm i body-parser -S
//引入解析post请求参数的模块
const bodyParser = require("body-parser")

// 解析表单数据application/x-www-form-urlencoded
// extended: true表示用qs模块来解析post数据,false表示用原生的queryString模块来解析
app.use(bodyParser.urlencoded({ extended: false }))
 
// 解析post请求以json格式传递的参数 application/json
app.use(bodyParser.json())


......

//添加商品
app.post("/product",(req,res)=>{
    //接收参数
    let { productName, price , imgUrl} = req.body;
    let sql = "insert into product (productName,price,imgUrl) values (?,?,?)"
    conn.query(sql,[productName, price , imgUrl],(err,result)=>{
        if (err){
            console.log('增加失败');
            return;
        }
        let data;
        if (result.affectedRows === 1){
            data = {
                code: 0,
                msg: '添加成功'
            }
        }else{
            data = {
                code: 1,
                msg: '添加失败'
            }
        }
        res.send(data)
    })
})

三、删除

前端代码

function delProduct() {
    let delProductBtn = $(".delProduct")
    delProductBtn.onclick = function () {
        let id = 42;
        axios.delete("/product", {
            params: {
                id
            }
        })
        .then((res) => {
            console.log(res.data);
        })
    }
}

后端代码

//删除商品
router.delete("/product",(req,res)=>{
    //接收参数
    let { id} = req.query;
    let sql = "delete from product where id = ?"
    conn.query(sql,[id],(err,result)=>{
        if (err){
            console.log('增加失败');
            return;
        }
        let data;
        if (result.affectedRows === 1){
            data = {
                code: 0,
                msg: '删除成功'
            }
        }else{
            data = {
                code: 1,
                msg: '删除失败'
            }
        }
        res.send(data)
    })
})

更新商品信息

前端代码

//单击按钮,修改商品
function updateProduct() {
    let updateProductBtn = $(".updateProduct")
    updateProductBtn.onclick = function () {
        let productInfo = {
            id: 38,
            productName: '护手霜',
            price: 23,
            imgUrl: '23.jpg'
        }
        axios.put("/product", productInfo)
        .then((res) => {
            console.log(res.data);
        })
    }
}

后端代码

//更新商品
router.put("/product",(req,res)=>{
    //接收参数
    
    let { id,productName,price,imgUrl} = req.body;
    console.log(req.body);
    let sql = "update product set productName=?,price=?,imgUrl=? where id = ?"
    conn.query(sql,[productName,price,imgUrl,id],(err,result)=>{
        if (err){
            console.log('服务器异常');
            return;
        }
        let data;
        if (result.affectedRows === 1){
            data = {
                code: 0,
                msg: '更新成功'
            }
        }else{
            data = {
                code: 1,
                msg: '更新失败'
            }
        }
        res.send(data)
    })
})
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 安装mysql模块 npm i mysql -S 在项目中引入mysql模块 const mysql = requ...
    alicemum阅读 4,251评论 0 0
  • Docker 安装、更新、卸载 gmg [后端工程师进阶](javascript:void(0);) 2018-1...
    堕落天使1996阅读 1,724评论 0 0
  • node.js 介绍 node.js是什么 node.js 是一个开发平台,就像java开发平台...何为开发平台...
    小浅_阅读 4,930评论 0 6
  • React Webpack使用 1.webpack简介 项目中可能有多个 .js、.css 、image、其他资源...
    Darling_a388阅读 1,670评论 0 2
  • express 库 http://www.expressjs.com.cn/ 干嘛的:nodejs库,不用基础做...
    百事皆可乐_5eed阅读 2,662评论 0 4

友情链接更多精彩内容