Adi*_*han 3 javascript middleware node.js express
这是我的代码在这里..!
const express = require('express');
const app = express();
let myFunc = function (req, res, next) {
console.log('This is middleware');
next();
}
app.use(myFunc);
app.get('/', (req, res) => {
console.log('This is get /');
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running at port 3000....');
});
Run Code Online (Sandbox Code Playgroud)
在此,我创建了一个名为 myFunc 的中间件,但输出并不像我想象的那样
Server is running at port 3000....
This is middleware
This is get /
This is middleware
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为浏览器正在请求两个文件。第一个将用于/,第二个可能用于favicon.ico。如果您想了解为什么要调用它,请将您的一个函数更改为如下所示:
let myFunc = function (req, res, next) {
console.log('This is middleware', req.originalUrl);
next();
}
Run Code Online (Sandbox Code Playgroud)
然后它会输出每次浏览器访问服务器时请求的 URL。
每次触发应用程序时,app.use 都会运行。在这种情况下,您会触发两次。app.get 和 app.listen