Express 极速掌握

中间件的写法

支持 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()); 不支持下面的提交

    image.png

    也就是
    Content-Type: application/json

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


    image.png

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。