Express Flashcards
What is express?
Express is a node.js framework, that provides higher level of abstraction and makes the development faster
It contains set of features:
- complex routing
- easier handling of requests and responses
- middleware,
- server-side rendering
Setting up express.
- It is a convention, to have all the express configuration files in app.js file.
- const express = require(‘express’);
// Setting up he app - const app = express();
- app.listen(port, callback);
Routing in express
When you set up your const app = express(), you can define basic routing, by app.get('/', (req, res) => { res.status(200).send('Hello'); })
However, for more complex application it is better to use Router object that is part of express.
In express, a router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.
- router.METHOD(path, [callback, …] callback),
where METHOD is one of the http methods such as get, put, post - router.all(path, [callback, …] callback),
This method is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs).
How do you setup a router object in express?
In express we can deal with routers in the following way:
- const express = require(‘express’);
- const router = express.Router(); // we grab the router off of exrpess.
- define all the routes.
To define routes,
1. we use
router.get(‘/’,(req, res, next) => {})
2. and provide a callback function that will run, whenever somebody visits that specific url.
req - object full of information that is coming in
res - object full of methods of saving data back to the user.
What are the differences between res.send(), res.json() and res.end() methods?
All of those methods are used to send responses using Express.
- res.send() and res.json() are almost identical. The difference is that res.json() will convert non objects to json.
res. json() has two additional options:
app. set(‘json replacer’, replacer); // property transformation rules
app. set(‘json spaces’, 2); // number of spaces for indentation
- we use res.end() if we want to end the response without providing any data. This could be useful for a 404 page.
How can you access request variables that are specified in the route in express?
To make endpoint that uses variables in a rout, we need to add a colon to the URL.
router.get(‘/reverse/:name’, (req, res) => {
res.send(req.params.name);
})
then the variable will be accessible in the req.params.name obj.
If the parameter is optional then we need to add a question mark to the parameter, like:
/api/v1/tours/:id/:y?
What is the order of the middleware functions in express?
IN express “everything is middleware” (even routers - which just are invoked when some conditions appear).
Middleware functions are the functions that happen inbetween the Request and Response (See The Request-Response Cycle).
The middleware functions that we use are in order that they are defined in the code.
app.use(func);
All the middleware that we use in our express app, are called the middleware stack.
What is mounting?
Mounting is a concept used in express to register middleware functions on a specific path. You can bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions.
However for most cases, you want to send responses based on the type of resource that has been requested.
This example shows a middleware function mounted on the /user/:id path. The function is executed for any type of HTTP request on the /user/:id path.
app.use(‘/user/:id’, function (req, res, next) {
console.log(‘Request Type:’, req.method)
next()
})
You can also define Router-level middleware with const router = express.Router().(use/METHOD)
How do you define Error handling middleware?
You define Error handling middleware, just as usual middleware, but they always take four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send(‘Something broke!’)
})
What is Param middleware?
Param middle ware is a middleware that only runs for certain parameters.
Param middleware has access to a 4th argument (value that the param returns).
router.param(‘id’, (req, res, next, val) => {
console.log(Tour id is: ${val}
);
next();
})
How do you add middlewares to specific METHOD handler stack?
In order, to add a middleware to handler stack for a specific METHOD, we just need to provide it as another argument. Like:
router.route(‘/’)
.get(tourController.getAlTours)
.post(middlewareFunc, tourController.createTour);
With this method, we can add multiple handlers to a stack.
How do you serve static files in express?
In order to serve static sites, we need to use a built in middleware and pass a folder location that is supposed to serve as a root
app.use(express.static(${\_\_dirname}/public
));
How do you handle unhandled routes in express?
Routers are mounted on specific routes.
Those routers are middlewares in an express app.
So if specific route does not match any mounted route, the express app will go to the next middleware defined by app.use.
Because the order of the middlewares determines the invokations order, if we add a handler for all the unhandled routes for .all requests as the last middleware in our express configuration, we will handle these routes. (If it matched a specific route, that we are handling in our api, we would exit the stack earlier)
app.all(‘*’, (req, res, next) => {
res.status(404).json({
status: ‘fail’,
message: Can't find ${req.originalUrl}
})
})
How do we handle errors in express?
Express comes with error handling out of the box.
We need to write an error handling middleware, which will catch errors coming from all over the application (no matter where its from).
app. use((err, req, res, next) => {
err. statusCode = err.statusCode || 500;
err. status = err.status || ‘error’;
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
});
In the middleware that produces an error, we can call next(err) with an err argument. Then express will assume, that whatever we passed is an error, and it will skip to our error handling middleware.
app.all('*', (req, res, next) => { const err = new Error(`Can't find ${req.originalUrl}`) err.status = 'fail'; err.statusCode = 404;
next(err)
});
How can you handle unhandled promise rejection in express app?
Each time that there is an unhandledRejection, the process object will emit an object called unhandledRejection.
We can subscribe to that event
process.on(‘unhandledRejection’ (err) => {
console.log(err.name,err.message);
server.close(()=>process.exit(1));
})