- 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.
- 程序員修煉之道:程序設計入門30講
- 復雜軟件設計之道:領域驅動設計全面解析與實戰(zhàn)
- 零起步玩轉掌控板與Mind+
- C#完全自學教程
- Getting Started with PowerShell
- Kotlin Standard Library Cookbook
- JSP開發(fā)案例教程
- Advanced Express Web Application Development
- 零基礎學C語言(第4版)
- 軟件工程與UML案例解析(第三版)
- Python第三方庫開發(fā)應用實戰(zhàn)
- SAP Web Dynpro for ABAP開發(fā)技術詳解:基礎應用
- Python自動化運維:技術與最佳實踐
- Ionic Framework By Example
- jMonkeyEngine 3.0 Cookbook