npm init -y(初始化项目)
npm install express(引入express)
npx express-generator -e(自动生成模板。添加对 ejs 模板引擎的支持)
app.js
const express=require("express"); const path=require("path"); const logger=require("morgan"); const app=express(); //创建Web应用 // app.get("/",(req,res,next)=>{ // res.send("Hello Express!"); // next(); // }) 挂载静态资源 app.use("/",express.static(path.join(__dirname,"/public"))); //挂载日子组件 app.use(logger("dev")); //设置视图文件的路径 app.set('views', path.join(__dirname, 'public')); //设置视图引擎为ejs app.set('view engine', 'ejs'); //挂载路由 const indexRouter=require("./router/index") app.use("/",indexRouter); const dogRouter=require("./router/dog") app.use("/dog",dogRouter); //获取query中的参数 app.get("/cart",(req,res,next)=>{ let id=req.query.id; res.send("Get,id="+id); }) //获取路径中的值 app.get("/cart/:id/:type",(req,res,next)=>{ let id=req.params.id; res.send(req.url+",id="+id+"type="+req.params.type); }) //挂载中间件函数 //如果不指明路径则匹配根路径 app.use("/",(req,res,next)=>{ console.log("当前时间:"+Date.now()); next(); }) module.exports=app;//导出对象
www.js
const app=require("../app.js"); app.listen(3000,"127.0.0.1",()=>{ console.log("Web应用运行中..."); })
./router/dog.js(设置路由)
const express=require("express"); //创建路由对象 const router=express.Router(); const _=require("lodash"); let dogs=[ {id:1,name:"金毛",price:1000}, {id:2,name:"阿拉斯加",price:1000}, {id:3,name:"比熊",price:1000}, {id:4,name:"泰迪",price:1000}, {id:5,name:"旺财",price:1000} ] router.get('/', function(req, res, next) { res.render('dog', { title: 'dog',dogs,msg:""}); }); router.get('/delete/:id', function(req, res, next) { //拿到索引 let index=_.findIndex(dogs,{id:parseInt(req.params.id)}); //删除 dogs.splice(index,1); //返回消息提示 res.render("dog",{ title: 'dog',dogs,msg:"删除成功"}) }); module.exports=router;
标签:Node,req,const,res,app,express,js,id From: https://www.cnblogs.com/zsbb/p/16706541.html