Express 极速掌握

 2023-09-05 阅读 84 评论 0

摘要:中间件的写法 支持 callback1,callback2、[callback1, callback2]、function callback(req, res, next) 或混合写法 function cb1(req, res, next) {console.log('--cb1--');next(); }function cb2(req, res, next) {console.log('--cb2--');next(); }app.ge

中间件的写法

支持 callback1,callback2、[callback1, callback2]、function callback(req, res, next) 或混合写法

function cb1(req, res, next) {console.log('--cb1--');next();
}function cb2(req, res, next) {console.log('--cb2--');next();
}app.get('/',cb1, [cb2],(req, res, next) => {console.log('--cb3--');next();},(req, res, next) => {res.send('hello');
});

middleware之间传值

使用 res.locals.key=value;

app.use(function(req, res, next) {res.locals.user = req.user;  res.locals.authenticated = ! req.user.anonymous;next();
});

传给下一个

app.use(function(req, res, next) {if (res.locals.authenticated) {console.log(res.locals.user.id);}next();
});

表单提交及json格式提交

var express = require('express');
var app = express();
var bodyParser = require('body-parser');// 支持解析json格式
app.use(bodyParser.json());// 支持解析 application/x-www-form-urlencoded 编码,就是表单提交
var urlencodedParser = bodyParser.urlencoded({ extended: false })// 这个urlencodedParser必须带,不然 request.body 为 undefined
app.post('/', urlencodedParser, function(request, response) {console.dir(request.body);response.send('It works');}
});
  • 不带 app.use(bodyParser.json()); 不支持下面的提交

    img_92ada4e24a346cc1ff833ff9ef8a3a9c.png
    image.png

    也就是
    Content-Type: application/json

  • 带 var urlencodedParser = bodyParser.urlencoded({ extended: false })


    img_b7fa0a729420496ffa100d1f98960195.png
    image.png

参考:
http://expressjs.com/en/resources/middleware/body-parser.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/32.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息