天天看點

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()); 不支援下面的送出
    Express 極速掌握

    image.png

    也就是

    Content-Type: application/json

  • 帶 var urlencodedParser = bodyParser.urlencoded({ extended: false })
    Express 極速掌握

參考:

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