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. Modbus转OPC

    在这里给大家介绍一种低成本的将Modbus RTU协议的串口设备接入到OPC UA的服务器呢? OPC全称是OLE(Object Linking and Embedding) for Process ...

  2. kubernetes之DaemonSet以及滚动更新

    1.什么是DaemonSet? 1.1DaemonSet是Pod控制器的又一种实现方式,用于在集群中的全部节点上同时运行一份指定的Pod资源副本,后续加入集群的节点也会自动创建一个相关的Pod对象,当 ...

  3. SElinux管理

    SElinux: 是Linux的一个强制访问控制的安全模块 SElinux的相关概念: 对象:文件.目录.进程.端口等 主体:进程称为主体 SElinux将所有的文件都赋予一个type类型的标签,所有 ...

  4. 【原创】Python 懂车帝口碑爬虫

    本文所有教程及源码.软件仅为技术研究.不涉及计算机信息系统功能的删除.修改.增加.干扰,更不会影响计算机信息系统的正常运行.不得将代码用于非法用途,如侵立删! 懂车帝综合口碑 需求 操作环境 win1 ...

  5. JVM学习之 内存结构

    目录 一.引言 1.什么是JVM? 2.学习JVM有什么用 3.常见的JVM 4.学习路线 二.内存结构 1. 程序计数器 1.1 定义 1.2作用 2. 虚拟机栈 2.1定义 2.2栈内存溢出 2. ...

  6. Luogu3870 [TJOI2009]开关 (分块)

    线段树做法很简单,但分块好啊 #include <iostream> #include <cstdio> #include <cstring> #include & ...

  7. 记一次 ClickHouse 性能测试

    前言 在工作场景中,我们会采集工厂设备数据用于智能控制,数据的存储用了 InfluxDB,随着数据规模越来越大,InfluxDB 的性能越来越差,故考虑引入 ClickHouse 分担 InfluxD ...

  8. day23--Java集合06

    Java集合06 13.Map接口02 13.2Map接口常用方法 put():添加 remove():根据键键删除映射关系 get():根据键获取值 size():获取元素个数 isEnpty(): ...

  9. 【SwiftUI】学习笔记1-创建第一个iOS应用

    本系列将会开发大量实际的项目. 系列为本人学习笔记,资料:<SwiftUI自学成长笔记>-刘铭 资源源代码下载资源:可以在gitee上下载,搜索刘铭即可. 第一章:创建项目 也可以在菜单栏 ...

  10. docker 匿名和具名挂载

    匿名挂载,只指定容器内了,没指定容器外 -v 容器内路径 docker run -d -P --name nginx01 -v /etc/nginx nginx #-P 随机映射端口 ; -v 不指定 ...