2021-09-15 Express+axios

express完整代码

// 第三方的模块(包)需要先安装,再引入
const express = require("express")
const mysql = require("mysql");

//实例化一个express的应用
const app = express()

//定义服务器监听的端口
const port = 3000
app.use(express.json())
app.use(express.urlencoded({extended:true}))
// 托管静态资源(public存放静态资源文件 )
app.use(express.static('public'))

let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'flowers',
    port: '3306'
});

// 实例的connect()方法将连接数据库
connection.connect();


app.get("/product", (req, res) => {
    let scene = req.query.scene
    console.log(scene);
    let sql = `select * from product where scene like '${scene}' order by Id desc limit 0,5`
    connection.query(sql, function (err, result) {
        if (err) {
            console.log('查询数据库失败');
        } else {
            var data;
            if (result.length) {
                data = {
                    code: 0,
                    list: result
                }
            } else {
                data = {
                    code: 1,
                    msg: '没有结果 '
                }
            }
            res.send(data)
        }
    })
})
app.post("/reg",(req,res)=>{
    console.log(req.body);
    res.send({
        msg: 'success'
    })
})
app.get("/reg",(req,res)=>{
    console.log('get',req.query);
    res.send({
        msg: 'success'
    })
})

var multipart = require('connect-multiparty');
 
var multipartMiddleware = multipart();

app.post('/register', multipartMiddleware, function(req, res) {
// app.post('/register',  function(req, res) {
    console.log('get FormData Params: ', req.body);
    res.json({
        id: 1
    })
})

app.delete('/del/:id',(req,res)=>{
    console.log('del',req.params);
    res.json({
        id: 1
    })
})

app.put("/pro",multipartMiddleware,(req,res)=>{
    console.log(req.body);
    res.json({
        id: 22222
    })
})
app.listen(port, () => {
    console.log(`服务器正在监听:localhost:${port}端口`)
})

Postman的使用

下载:https://www.postman.com/downloads/

post请求参数如果选择raw, 应填写标准的json数据,如 {"id":123}

定义Express中RestFul风格的API

get请求: 查询信息

app.get("/product",(req,res)=>{
    //接收请求参数
    console.log('get',req.query);
    res.send({
        msg: 'success'
    })
})

或者

app.get("/product/:id",(req,res)=>{
    //接收请求参数
    console.log('get',req.params);
    res.send({
        msg: 'success'
    })
})

post请求: 新增信息

处理post请求时,需要添加代码

app.use(express.json())
app.use(express.urlencoded({extended:true}))

......
app.post("/product",(req,res)=>{
    //接收请求参数
    console.log('post',req.body);
    res.send({
        msg: 'success'
    })
})

如果post请求数据格式为form-data(Postman中),则需安装connect-multiparty包

var multipart = require('connect-multiparty');
 
var multipartMiddleware = multipart();
app.post('/product', multipartMiddleware, function(req, res) {
    console.log('get FormData Params: ', req.body);
    res.json({
        id: 1
    })
})

put请求: 修改信息

和post请求相似

app.put("/product",(req,res)=>{
    //接收请求参数
    console.log('post',req.body);
    res.send({
        msg: 'success'
    })
})

delete请求: 删除信息

和get请求相似

app.get("/product",(req,res)=>{
    //接收请求参数
    console.log('get',req.query);
    res.send({
        msg: 'success'
    })
})

原生ajax请求 (了解)

前端axios工具的使用

get请求

axios.get("http://localhost:3000/product", {
    params: {
        id: 1
    }
})
    .then((res) => {
        console.log(res.data);
    })
    .catch((err) => {
        console.log(err);
    })

//或者
axios.get("http://localhost:3000/product/1")
    .then((res) => {
        console.log(res.data);
    })
    .catch((err) => {
        console.log(err);
    })

post请求

axios.post("http://localhost:3000/product",{
            name: 'a',
            price: 100
        })
        .then((res)=>{
            console.log(res.data);
        })

put请求

axios.put("http://localhost:3000/product",{
            name: 'a',
            price: 100
        })
        .then((res)=>{
            console.log(res.data);
        })

delete请求

axios.delete("http://localhost:3000/product", {
    params: {
        id: 1
    }
})
    .then((res) => {
        console.log(res.data);
    })
    .catch((err) => {
        console.log(err);
    })

//或者
axios.delete("http://localhost:3000/product/1")
    .then((res) => {
        console.log(res.data);
    })
    .catch((err) => {
        console.log(err);
    })

Express的数据库访问

查询

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)
        }
    })
})

新增

//添加商品
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)
    })
})

修改

//更新商品
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)
    })
})

删除

//删除商品
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)
    })
})

你可能感兴趣的:(2021-09-15 Express+axios)