Answer the question
In order to leave comments, you need to log in
What is called middleware in express?
Constantly in all articles and documentation related to Express.js I meet the word middleware, I just can’t understand what it means and why it is needed, although this ignorance does not prevent me from writing applications in express. Translated as "intermediate processing functions", one gets the feeling that I just wanted to come up with a term and that's it. They call them functions like app.use() app.get(). In the documentation, this word is probably used more often than the space character. Another question arises, what is not middleware at all? Maybe it would be better to call this word express.
Answer the question
In order to leave comments, you need to log in
Middleware - translated as "intermediate layer". In fact, this is a function through which requests automatically pass. You can set the functions through which all requests will pass without exception, or you can assign these functions to specific requests.
I would also add that this layer (which is user-defined) is optional, but it is convenient to use it to perform some additional logic. For example, you need to check all requests for satisfaction of a certain condition and redirect the request to another address if necessary.
let a = 11
app.use('/', function middleware(req, res, next) { //в пеовом middleware делаем вычисления
a = 11 + 4;
next() //Идём дальше
}, function otherMiddleware (req, res, next) { //В этом middleware выводим значение
if(req.url == '/') { // Проверяем существует ли url
res.send(`Hello world ${a}`) // Отправляем значение, если есть
} else {
next() // Идём дальше. Например на функцию, которая отобразит 404
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question