官术网_书友最值得收藏!

Using Express.js middleware

Express.js provides great ways to write efficient back ends without duplicating code.

Every middleware function receives a request, a response, and next. It needs to run next to pass control further to the next handler function. Otherwise, you will receive a timeout. Middleware allows us to pre- or post-process the request or response object, execute custom code, and much more. We previously covered a simple example of handling requests in Express.js.

Express.js can have multiple routes for the same path and HTTP method. The middleware can decide which function should be executed.

The following code is an easy example showing what can generally be accomplished with Express.js:

  1. The root path '/' is used to catch any request.
app.get('/', function (req, res, next) {
  1. We randomly generate a number with Math.random between 1 and 10.
var random = Math.random() * (10 -1) + 1;
  1. If the number is higher than 5, we run the next('route') function to skip to the next app.get with the same path. 
if (random > 5) next('route')

This route will log us 'second'.

  1. If the number is lower than 0.5, we execute the next function without any parameters and go to the next handler function. This handler will log us 'first'.
  else next()
}, function (req, res, next) {
res.send('first');
})

app.get('/', function (req, res, next) {
res.send('second');
})

You do not need to copy this code as it is just an explanatory example. This functionality can come in handy when covering special treatments such as admin users and error handling.

主站蜘蛛池模板: 县级市| 峨眉山市| 海晏县| 鲁山县| 沧源| 龙井市| 慈利县| 洱源县| 汕尾市| 康乐县| 德令哈市| 扶沟县| 安康市| 山东省| 邵武市| 泰兴市| 吉林市| 萨嘎县| 高雄县| 库尔勒市| 永新县| 巫溪县| 大同市| 阳江市| 云和县| 广宁县| 沙坪坝区| 郎溪县| 濉溪县| 湛江市| 图木舒克市| 红原县| 额济纳旗| 郧西县| 上虞市| 嘉定区| 侯马市| 昌吉市| 阿瓦提县| 虞城县| 江西省|