Express 极速掌握

本文介绍Express.js中中间件的多种写法及其之间的数据传递方式,并演示如何使用body-parser中间件处理JSON和表单提交的数据。

中间件的写法

支持 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值