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

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.

主站蜘蛛池模板: 于都县| 铜川市| 金沙县| 西峡县| 徐汇区| 宜城市| 上栗县| 凌海市| 阳朔县| 酉阳| 佳木斯市| 崇左市| 资中县| 林州市| 东丽区| 浪卡子县| 城固县| 余姚市| 美姑县| 利津县| 嵊州市| 五指山市| 平和县| 泊头市| 临清市| 黎平县| 通辽市| 利川市| 岗巴县| 图们市| 岳阳县| 金川县| 额敏县| 张家港市| 成武县| 孟连| 屯留县| 平度市| 奉贤区| 葫芦岛市| 甘南县|