Express 的中间件

中间件是 Express 强大的功能,它的处理流程示意图如下:

下面是一个演示例子:

const app = express()

app.use((request, response, next) => {
  console.log(request.headers)
  next()
})

app.use((request, response, next) => {
  request.chance = Math.random()
  next()
})

app.get('/', (request, response) => {
  response.json({
    chance: request.chance
  })
})

app.listen(3000)

实际用浏览器访问 3000 端口,显示:

{"chance":0.8529619111949602}

而同时服务器将输出 headers 信息:

{ host: ‘localhost:3000’,
‘cache-control’: ‘max-age=0’,
‘upgrade-insecure-requests’: ‘1’,
‘user-agent’:
‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36’,
accept:
‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8’,
‘accept-encoding’: ‘gzip, deflate, br’,
‘accept-language’: ‘en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6,fr;q=0.5’,
cookie:
‘has_js=1; ctools-collapsible-state=views-ui-advanced-column-admin_views_user%3A1; Hm_lvt_2d54c596600855c513c1de8d3089cf49=1538104503; SSESS960dd94e6e0eab64e7dbcdfad8142289=WbnIkGEIr9MGdzBokDMy7UrlKcrgr4hhm6EwsLCCsbg; SSESS7d63066bea9bdf15ce0080dff232aa6c=DxwEDQt6ORpSS2F87g5UaUXbygyMUBguNelNkYS6OWc; Hm_lpvt_2d54c596600855c513c1de8d3089cf49=1540029734’,
‘if-none-match’: ‘W/“1d-IU1lU9zvODrZ9dfXuBelZ3nTeGw”’,
‘x-forwarded-for’: ‘114.223.51.198’,
‘x-forwarded-host’: ‘abc.com’,
‘x-forwarded-server’: ‘abc.com’,
connection: ‘Keep-Alive’ }

https://blog.risingstack.com/your-first-node-js-http-server/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值