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

Ordering of middleware

Express doesn't know what middleware components do internally, so it doesn't reorder them. The framework doesn't try to be overly smart and do complicated things such as checking whether a function depends on another. This means it's our responsibility to make sure we load them in the proper order.

The most popular example to reflect this is the session and cookie middleware. The session handler uses a cookie as an ID to retrieve the session data, so the cookie parsing must take place in advance. The same dependency relation is between the cross-site request forgery (CSRF) and session middleware, since the first stores its token on the user's session. An example with the correct inclusion of these three middleware components is as follows:

var cookieParser = require('cookie-parser');
var session = require('express-session');
var csrf = require('csurf');

app.use(cookieParser());
app.use(session({
  secret: 'random chars here'
}));
app.use(csrf());

There are other reasons for paying attention to the ordering of middleware besides taking care of dependencies, such as the need for authentication. For example, if only certain white-listed IP addresses are allowed to view a certain page, and the component that's doing the authentication is placed after the one that renders that page, then everyone will be able to bypass the authentication. Actually, a better way to say this is that nobody (no request) would ever reach the authentication layer in the first place.

You might be wondering what is the difference between app.VERB() and regular middleware loaded with app.use(). The fact of the matter is that both methods delegate to the router introduced in Express 4 and behave similarly, with a few exceptions, such as the following:

  • The path parameter is stripped and not visible to the middleware function for app.use()
  • The app.VERB() function accepts multiple callbacks instead of just one
主站蜘蛛池模板: 扶风县| 海伦市| 郎溪县| 霍山县| 名山县| 融水| 上蔡县| 溆浦县| 天等县| 泾源县| 东辽县| 哈巴河县| 临沂市| 柳州市| 上林县| 绵阳市| 大渡口区| 墨竹工卡县| 梁山县| 大余县| 白朗县| 鲁甸县| 新沂市| 响水县| 新巴尔虎右旗| 仙桃市| 安新县| 青龙| 昌吉市| 桓仁| 铅山县| 武威市| 岳西县| 禄丰县| 青阳县| 梓潼县| 克东县| 永寿县| 金寨县| 盐边县| 体育|