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

Managing routes

The input of our application is the routes. The user visits our page at a specific URL and we have to map this URL to a specific logic. In the context of Express, this can be done easily, as follows:

var controller = function(req, res, next) {
  res.send("response");
}
app.get('/example/url', controller);

We even have control over the HTTP's method, that is, we are able to catch POST, PUT, or DELETE requests. This is very handy if we want to retain the address path but apply a different logic. For example, see the following code:

var getUsers = function(req, res, next) {
  // ...
}
var createUser = function(req, res, next) {
  // ...
}
app.get('/users', getUsers);
app.post('/users', createUser);

The path is still the same, /users, but if we make a POST request to that URL, the application will try to create a new user. Otherwise, if the method is GET, it will return a list of all the registered members. There is also a method, app.all, which we can use to handle all the method types at once. We can see this method in the following code snippet:

app.all('/', serverHomePage);

There is something interesting about the routing in Express. We may pass not just one but many handlers. This means that we can create a chain of functions that correspond to one URL. For example, it we need to know if the user is logged in, there is a module for that. We can add another method that validates the current user and attaches a variable to the request object, as follows:

var isUserLogged = function(req, res, next) {
  req.userLogged = Validator.isCurrentUserLogged();
  next();
}
var getUser = function(req, res, next) {
  if(req.userLogged) {
    res.send("You are logged in. Hello!");
  } else {
    res.send("Please log in first.");
  }
}
app.get('/user', isUserLogged, getUser);

The Validator class is a class that checks the current user's session. The idea is simple: we add another handler, which acts as an additional middleware. After performing the necessary actions, we call the next function, which passes the flow to the next handler, getUser. Because the request and response objects are the same for all the middlewares, we have access to the userLogged variable. This is what makes Express really flexible. There are a lot of great features available, but they are optional. At the end of this chapter, we will make a simple website that implements the same logic.

主站蜘蛛池模板: 清涧县| 天津市| 鸡泽县| 邵阳市| 方山县| 通化市| 麦盖提县| 新龙县| 驻马店市| 化德县| 什邡市| 搜索| 胶州市| 安泽县| 潜江市| 都江堰市| 神农架林区| 东阳市| 西宁市| 阿拉善盟| 林州市| 青海省| 五常市| 神农架林区| 尼勒克县| 黄骅市| 黄浦区| 子洲县| 汉中市| 吐鲁番市| 涞源县| 阜平县| 天水市| 宕昌县| 西吉县| 阳江市| 磐安县| 离岛区| 平远县| 福鼎市| 晋州市|