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

  • Node.js Blueprints
  • Krasimir Tsonev
  • 403字
  • 2021-07-16 11:36:15

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.

主站蜘蛛池模板: 孟村| 泌阳县| 焉耆| 富宁县| 万盛区| 吉安市| 通化县| 日土县| 彭泽县| 鲁甸县| 贵溪市| 永靖县| 海门市| 镇原县| 苍南县| 平舆县| 吉水县| 毕节市| 边坝县| 长阳| 修武县| 雷波县| 特克斯县| 政和县| 阳信县| 名山县| 昌江| 济南市| 中牟县| 民乐县| 河间市| 报价| 涟水县| 山阴县| 天津市| 吉安县| 财经| 安仁县| 新蔡县| 巴林右旗| 合肥市|