npm init -y(初始化项目)

npm install express(引入express)

npx express-generator -e(自动生成模板。添加对 ejs 模板引擎的支持)

npm i --save lodash(引入lodash)

 

路由配置carApi.js

const express=require("express");
let router=express.Router();
const _=require("lodash");

var cars=[];
cars.push({id:201701,name:"BMW",price:190,speed:"210km/h",color:"白色"});
cars.push({id:201702,name:"BYD",price:25,speed:"160km/h",color:"红色"});
cars.push({id:201703,name:"Benz",price:300,speed:"215km/h",color:"蓝色"});
cars.push({id:201704,name:"Honda",price:190,speed:"170km/h",color:"黑色"});
cars.push({id:201705,name:"QQ",price:130,speed:"210km/h",color:"白色"});

//Get
router.get("/",(req,res,next)=>{
    res.json({status:"ok","data":cars});
})
//查找单个汽车根据名称
router.get("/:name",(req,res,next)=>{
    //查找编号为id的汽车
    let car=_.filter(cars,{name:req.params.name})
    res.json({"data":car});
})
//查找单个汽车根据id
router.get("/edit/:id",(req,res,next)=>{
    //查找编号为id的汽车
    let car=_.find(cars,{id:parseInt(req.params.id)})
    res.json({status:"ok","data":car});
})
//排序
router.get("/order/orderBy",(req,res,next)=>{
    let car=_.orderBy(cars,["id"],["desc"]);
    console.log(car);
    res.json({status:"ok","data":car});
})
//Post
router.post("/",(req,res,next)=>{
    let car=req.body;
    let obj=_.last(_.sortBy(cars,["id"]));
    car.id=obj.id+1;
    cars.push(car);
    res.json({status:"ok","data":car});
})

//Put
router.put("/",(req,res,next)=>{
    let srcCar=req.body;
    let car=_.find(cars,{id:parseInt(srcCar.id)})
    car.name=srcCar.name;
    car.speed=srcCar.speed;
    car.price=srcCar.price;
    car.color=srcCar.color;
    res.json({status:"ok","data":car})
})

//Delete
router.delete("/:id",(req,res,next)=>{
    let indnx=_.findIndex(cars,{id:parseInt(req.params.id)})
    cars.splice(indnx,1)
    res.json({status:"ok","data":""})
})

module.exports=router;

 

cars.js配置ejs

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('cars', {});
});

module.exports = router;

 

app.js全局配置

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 carApiRouter = require('./routes/carApi');
var carRouter = require('./routes/cars');


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('/index', indexRouter);
app.use('/users', usersRouter);
app.use('/api/cars', carApiRouter);
app.use('/', carRouter);

let stus=[
  {id:202201,name:"tom",age:18},
  {id:202202,name:"rose",age:16},
  {id:202203,name:"jack",age:20},
  {id:202204,name:"lili",age:15},
  {id:202205,name:"lucy",age:15}
];

app.get("/stus",(req,res,next)=>{
  res.json(stus);
})



// 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;

cars.ejs页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>汽车管理系统</title>
</head>
<body>
<div id="app">
    <h2>汽车管理系统</h2>
    <div style="text-align:center">
    <input type="text" name="" id="" placeholder="请输入你要搜索的汽车" v-model="name" style="margin-bottom: 20px;width: 30%;padding: 7px 20px;border-radius: 20px;outline: none;border: 1px solid #666;">
    <button @click="search">搜索</button>
    <button @click="order">升序</button>
    <button @click="orderBy">降序</button>
</div>
   <table border="1" width="100%">
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>价格</th>
        <th>车速</th>
        <th>颜色</th>
        <th>操作</th>
    </tr>
    <tr v-for="(car,i) in cars" style="text-align: center;">
        <td>{{car.id}}</td>
        <td>{{car.name}}</td>
        <td>{{car.price}}</td>
        <td>{{car.speed}}</td>
        <td>{{car.color}}</td>
        <td>
            <a href="" @click.stop.prevent="del(car,i)">删除</a>
            <a href="" @click.stop.prevent="edit(car,i)">修改</a>
        </td>
    </tr>
   </table>
   <fieldset>
    <legend>添加汽车</legend>
    <p>
        <label>
            名称
            <input type="text" v-model="car.name">
        </label>
    </p>
    <p>
        <label>
            价格
            <input type="text" v-model="car.price">
        </label>
    </p>
    <p>
        <label>
            车速
            <input type="text" v-model="car.speed">
        </label>
    </p>
    <p>
        <label>
            颜色
            <input type="text" v-model="car.color">
        </label>
    </p>
    <p>
        <button @click="save" type="button">保存</button>
    </p>
   </fieldset>
</div>
</body>
<script src="javascripts/vue/vue.min.js"></script>
<script src="javascripts/axios/axios.js"></script>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            cars:[],
            car:{id:0,name:"",price:"",speed:"",color:""},
            name:"",
        },
        methods:{
            order(){
               this.carInfo();
            },
            orderBy(){
                axios.get("http://127.0.0.1:3000/api/cars/order/orderBy")
                .then(respons=>{
                    app.cars=respons.data.data;
                    console.log(this.cars);
                })
                .catch(err=>{
                    throw err;
                })
            },
            search(){
                if(this.name==""){
                    this.carInfo();
                }else{
                    axios.get("http://127.0.0.1:3000/api/cars/"+this.name)
                .then(respons=>{
                    app.cars=[respons.data.data];
                    console.log(this.cars);
                })
                .catch(err=>{
                    throw err;
                })
                }
                
            },
            carInfo(){
                axios.get("http://127.0.0.1:3000/api/cars/"+this.name)
                .then(respons=>{
                    this.cars=respons.data.data;
                })
                .catch(err=>{
                    throw err;
                })
            },
            del(car,i){
                if(confirm("你确定要删除吗?")){
                    let url="http://127.0.0.1:3000/api/cars/"+car.id
                        axios.delete(url)
                        .then(data=>{
                            if(data.data.status==="ok"){
                                alert("删除成功")
                                this.cars.splice(i,1);
                            }else{
                                alert("删除失败")
                            }
                        })
                        .catch(err=>{
                            throw err;
                        })
                }  
                return false;
            },
            edit(car,i){
                let url="http://127.0.0.1:3000/api/cars/edit/"+car.id
                        axios.get(url)
                        .then(data=>{
                           this.car=data.data.data;
                        })
                        .catch(err=>{
                            throw err;
                        })
            },
            save(){
                if(this.car.id){
                    axios.put("http://127.0.0.1:3000/api/cars",app.car)
                    .then(respons=>{
                        if(respons.data.status==="ok"){
                            alert("修改成功!")
                            this.car.id=0;
                            this.car.name="";
                            this.car.price="";
                            this.car.speed="";
                            this.car.color="";
                            this.carInfo();
                        }
                    })
                    .catch(err=>{
                        throw err;
                    })
                }else{
                    axios.post("http://127.0.0.1:3000/api/cars",this.car)
                    .then(respons=>{
                        if(respons.data.status==="ok"){
                            alert("添加成功!")
                            app.cars.push(respons.data.data)
                            this.car.id=0;
                            this.car.name="";
                            this.car.price="";
                            this.car.speed="";
                            this.car.color="";
                            this.carInfo();
                        }
                    })
                    .catch(err=>{
                        throw err;
                    })
                }
            }
        },
        created(){
           this.carInfo();
        },
    })
</script>
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>汽车管理系统</title>
</head>
<body>
<div id="app">
    <h2>汽车管理系统</h2>
    <div style="text-align:center">
    <input type="text" name="" id="" placeholder="请输入你要搜索的汽车" v-model="name" style="margin-bottom: 20px;width: 30%;padding: 7px 20px;border-radius: 20px;outline: none;border: 1px solid #666;">
    <button @click="search">搜索</button>
    <button @click="order">升序</button>
    <button @click="orderBy">降序</button>
</div>
   <table border="1" width="100%">
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>价格</th>
        <th>车速</th>
        <th>颜色</th>
        <th>操作</th>
    </tr>
    <tr v-for="(car,i) in cars" style="text-align: center;">
        <td>{{car.id}}</td>
        <td>{{car.name}}</td>
        <td>{{car.price}}</td>
        <td>{{car.speed}}</td>
        <td>{{car.color}}</td>
        <td>
            <a href="" @click.stop.prevent="del(car,i)">删除</a>
            <a href="" @click.stop.prevent="edit(car,i)">修改</a>
        </td>
    </tr>
   </table>
   <fieldset>
    <legend>添加汽车</legend>
    <p>
        <label>
            名称
            <input type="text" v-model="car.name">
        </label>
    </p>
    <p>
        <label>
            价格
            <input type="text" v-model="car.price">
        </label>
    </p>
    <p>
        <label>
            车速
            <input type="text" v-model="car.speed">
        </label>
    </p>
    <p>
        <label>
            颜色
            <input type="text" v-model="car.color">
        </label>
    </p>
    <p>
        <button @click="save" type="button">保存</button>
    </p>
   </fieldset>
</div>
</body>
<script src="javascripts/vue/vue.min.js"></script>
<script src="javascripts/axios/axios.js"></script>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            cars:[],
            car:{id:0,name:"",price:"",speed:"",color:""},
            name:"",
        },
        methods:{
            order(){
               this.carInfo();
            },
            orderBy(){
                axios.get("http://127.0.0.1:3000/api/cars/order/orderBy")
                .then(respons=>{
                    app.cars=respons.data.data;
                    console.log(this.cars);
                })
                .catch(err=>{
                    throw err;
                })
            },
            search(){
                if(this.name==""){
                    this.carInfo();
                }else{
                    axios.get("http://127.0.0.1:3000/api/cars/"+this.name)
                .then(respons=>{
                    app.cars=[respons.data.data];
                    console.log(this.cars);
                })
                .catch(err=>{
                    throw err;
                })
                }
               
            },
            carInfo(){
                axios.get("http://127.0.0.1:3000/api/cars/"+this.name)
                .then(respons=>{
                    this.cars=respons.data.data;
                })
                .catch(err=>{
                    throw err;
                })
            },
            del(car,i){
                if(confirm("你确定要删除吗?")){
                    let url="http://127.0.0.1:3000/api/cars/"+car.id
                        axios.delete(url)
                        .then(data=>{
                            if(data.data.status==="ok"){
                                alert("删除成功")
                                this.cars.splice(i,1);
                            }else{
                                alert("删除失败")
                            }
                        })
                        .catch(err=>{
                            throw err;
                        })
                }  
                return false;
            },
            edit(car,i){
                let url="http://127.0.0.1:3000/api/cars/edit/"+car.id
                        axios.get(url)
                        .then(data=>{
                           this.car=data.data.data;
                        })
                        .catch(err=>{
                            throw err;
                        })
            },
            save(){
                if(this.car.id){
                    axios.put("http://127.0.0.1:3000/api/cars",app.car)
                    .then(respons=>{
                        if(respons.data.status==="ok"){
                            alert("修改成功!")
                            this.car.id=0;
                            this.car.name="";
                            this.car.price="";
                            this.car.speed="";
                            this.car.color="";
                            this.carInfo();
                        }
                    })
                    .catch(err=>{
                        throw err;
                    })
                }else{
                    axios.post("http://127.0.0.1:3000/api/cars",this.car)
                    .then(respons=>{
                        if(respons.data.status==="ok"){
                            alert("添加成功!")
                            app.cars.push(respons.data.data)
                            this.car.id=0;
                            this.car.name="";
                            this.car.price="";
                            this.car.speed="";
                            this.car.color="";
                            this.carInfo();
                        }
                    })
                    .catch(err=>{
                        throw err;
                    })
                }
            }
        },
        created(){
           this.carInfo();
        },
    })
</script>
</html>
posted on 2022-09-19 11:34  最帅爸爸  阅读(113)  评论(0)    收藏  举报