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;
标签:Node,res,name,car,req,js,json,cars,id From: https://www.cnblogs.com/zsbb/p/16707173.html