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>

最新文章

  1. 1-安装kvm及虚拟机
  2. jquery EasyUI
  3. [原创]Matlab生成随机数
  4. C 语言中 free() 函数简单分析
  5. 重载PostNcDestroy()函数做一些清理工作
  6. Windows编写bat执行文件
  7. php类的实现
  8. [开心IT面试题] realloc用法
  9. rsyslog 传输mysql 日志
  10. hdu 4472 Count (递推)
  11. href 做导航 特效
  12. JDBC基础学习(五)&mdash;批处理插入数据
  13. Java中的的画正三角方法
  14. 18. 4Sum(中等)
  15. HighChar 案例
  16. Hystrix是个什么玩意儿
  17. linux ps 按进程消耗内存资源大小排序
  18. Windows平台最方便最易用的法语输入法
  19. Python学习笔记系列——函数
  20. 程序猿必备技能:数据库管理——关于MySQL

热门文章

  1. 重写并自定义依赖的原生的Bean方法
  2. PHP,javascript实现大文件上传
  3. mac 无任何来源选项
  4. Windows下安装新硬盘
  5. Angular 新建项目错误:The Schematic workflow failed. See above
  6. 【Java面试】Java有几种文件拷贝方式,哪一种效率最高?
  7. BZOJ3295/Luogu3157 [CQOI2011]动态逆序对 (CDQ or 树套树 )
  8. MySQL 数据操纵语句
  9. idea中无法在@Test 之下使用Scanner
  10. 【Java】学习路径49-练习:使用两个不同的线程类实现买票系统