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>

Node.js(四)json的更多相关文章

  1. Node.js 返回 JSON 数据

    Node.js 返回 JSON 数据 request.end([data[, encoding]][, callback]) var http = require('http'); const log ...

  2. Node.js返回JSON

    在使用JQuery的Ajax从服务器请求数据或者向服务器发送数据时常常会遇到跨域无法请求的错误,常用的解决办法就是在Ajax中使用JSONP.基于安全性考虑,浏览器会存在同源策略,然而<scri ...

  3. Update Node.js Package.json

    Update the latest package while using node.js, follow the command as following. npm i -g npm-check-u ...

  4. [转]Node.JS package.json 字段全解析

    Name 必须字段. 小提示: 不要在name中包含js, node字样: 这个名字最终会是URL的一部分,命令行的参数,目录名,所以不能以点号或下划线开头: 这个名字可能在require()方法中被 ...

  5. [读书笔记]了不起的node.js(四)

    这周的学习主要是nodejs的数据库交互上,并使用jade模板一起做了一个用户验证的网站.主要是遇到了一下几个问题. 1.mongodb版本过低 npm ERR! Not compatible wit ...

  6. node.js存json数据到mysql

    众所周知,mysql是无法存储json数据的,这个刚开始笔者也是知道的,也知道JSON.stringify()这个API的,但是当我真正要这样做利用JSON.stringify()讲要转换的JSON数 ...

  7. node.js(四)path优化(路径优化)

    1.normalize函数的基本用法 normalize函数将不符合规范的路径经过格式化转换为标准路径,解析路径中的.与..外,还能去掉多余的斜杠. 如下示例: var path = require( ...

  8. Node.js连接MySQL数据库及构造JSON的正确姿势

    做一下整理,以前也很随意的引入包链接数据库,后来发现常常连接出问题,异常退出,后来使用在网上一个方法解决问题,网址由于书签丢失,抱歉不能引用了.再有就是简单的模块化下,使得目录合理点,再有就是说明一下 ...

  9. 一名全栈工程师Node.js之路-转

    Node.js 全球现状 虽然 Node.js 在国内没有盛行,但据 StackOverflow 2016 年开发者调查,其中 node.js .全栈.JavaScript 相关的技术在多个领域(包括 ...

  10. 用 Node.js 把玩一番 Alfred Workflow

    插件地址(集成Github.掘金.知乎.淘宝等搜索) 作为 Mac 上常年位居神器榜第一位的软件来说,Alfred 给我们带来的便利是不言而喻的,其中 workflow(工作流) 功不可没,在它上面可 ...

随机推荐

  1. SQL语句的整合

    基础语法 https://blog.csdn.net/m0_37989980/article/details/103413942 CRUD 提供给数据库管理员的基本操作,CRUD(Create, Re ...

  2. flush方法和close方法的区别和字符输出流写数据的其他方法和字符输出流的续写和换行

    flush方法和close方法的区别 flush:刷新缓冲区,流对象可以继续使用 close:先刷新缓冲区,然后通知系统释放资源.刘对象不可以再被使用了. public class demo02 { ...

  3. HashSet存储自定义数据类型和LinkedHashSet集合

    HashSet存储自定义数据类型 public class Test{ /** * HashSet存储自定义数据类型 * set集合保证元素唯一:存储的元素(String,Integer,Studen ...

  4. DBPack SQL Tracing 功能及数据加密功能详解

    上周,我们正式发布了 DBPack SQL Tracing 功能和数据加密功能,现对这两个功能做如下说明. SQL Tracing 通过 DBPack 代理开启的全局事务,会自动在 http head ...

  5. Vue 路由的简单使用(命名路由、query路由传参、params路由传参)

    1 # Vue 路由 2 # 1.理解:一个路由(toute)就是一组映射关系(key-value),多个路由需要路由器(router)进行管理 3 # 2.前端路由:key是路径,value是组件 ...

  6. MVCC多版本并发控制的理解

    前置知识 当前读与快照读 当前读 什么是当前读:读取的是最新的数据,不会读到老数据. 何时触发:update.insert.delete.select lock in share mode.selec ...

  7. CMAKE编译时如何自动下载第三方库并解压、安装到指定目录

    GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源. 导语 在日常开发过程中难免会使用到第三方库或者需要将部分库分离另外存储,如果将库与代码放在一起难免会造成工程庞大,此时就可 ...

  8. 什么是hive的静态分区和动态分区,它们又有什么区别呢?hive动态分区详解

    面试官问我,什么是hive的静态分区和动态分区,这题我会呀. 简述 分区是hive存放数据的一种方式,将列值作为目录来存放数据,就是一个分区,可以有多列. 这样查询时使用分区列进行过滤,只需根据列值直 ...

  9. 原生js也可以自定义组件

    Web Components 是一套不同的技术,允许您创建可重用的定制元素(它们的功能封装在您的代码之外)并且在您的web应用中使用它们. 它由三项主要技术组成,它们可以一起使用来创建封装功能的定制元 ...

  10. 分库分表之ShardingSphere

    目录 分库分表诞生的前景 分库分表的方式(垂直拆分,水平复制) 1.垂直拆分 1.1 垂直分库 1.2 垂直分表 2.水平拆分 2.1 水平分库 2.2 水平分表 分库分库中间件 ShardingSp ...