1.next
可以传入多个函数 上个函数必须要next 下一步
可以对一个请求,进行多步处理
那就可以提取出一个模块 类似路由守卫的概念
app.get("/getData", function (req, res, next) { //上层函数预处理 些东西 req.x = "测试" next() //这里不写next 下面的不会执行 }, function (req, res, next) { // res.send("123") res.send("hello" + req.x) })
提取出函数
其实类似登录验证的思想 后续详讲
var login = true function isLogin(req, res, next) { req.name = "yzs" if (login) { // res.send("登录成功") next() } else { res.redirect("./login") } } app.get("/getData", isLogin, function (req, res) { res.send("hello-getData:" + req.name) }) app.get("/info", isLogin, function (req, res) { res.send("hello-info:" + req.name) })
2.use
设置静态资源目录也是因为所有请求过来都会执行这个函数
对于任何请求都会执行回调函数
作用: 对请求或响应对象进行扩展
调用中间件
app.use(function(req, res,next) { req.yzs = "厚德载物" console.log("厚积薄发"); // 不要写send 后面就不执行了 // res.send("返回") next() }) //后续每个请求都会调用 app.get("/getData",function(req,res){ res.send(req.yzs.toString()) })
3.post
传统方式
app.post("/message",function(req,res){ var str = "" req.on("data",function(chunk){ str +=chunk }) req.on("end",function(){ console.log("str:",str); res.send("------------") }) })
中间件封装 自定义
app.use(function(req, res,next) { console.log("中间件"); var str = "" req.on("data",function(chunk){ str +=chunk }) req.on("end",function(){ console.log("str:",str); req.body = str next() }) }) //post里面就可以直接获取body app.post("/msg",function(req,res){ res.send(req.body) })
4.body-parser
use调用中间件
const bodyparser = require('body-parser') //上篇文章的 use调用中间件 app.use(bodyparser.json()) app.use(bodyparser.urlencoded({extended:true})) app.post('/msg',function(req,res){ console.log("req:",req.body); res.send("123") })
5. express
//解析 for parsing application/json app.use(express.json()) //解析 for parsing application/x-www-form-urlencoded app.use(express.urlencoded({extended:true})) app.post('/msg',function(req,res){ console.log("req:",req.body); res.send("123") })