[英]Why function declaration doesn't work in app.use?
When I use foo
function declaration in app.use
as a middleware the compiler doesn't seem to recognize the req, res, next
variables:当我在
app.use
使用foo
函数声明作为中间件时,编译器似乎无法识别req, res, next
变量:
var express = require('express');
var path = require('path');
var app = express();
function foo (req, res, next){ // the middleware
console.log(req.path);
}
app.use('/', foo(req, res, next)); //ReferenceError: req is not defined
app.use('/', express.static("./public"));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
By comparison if I use function declaration inside app.use
the code works as intended:相比之下,如果我在
app.use
使用函数声明,则代码按预期工作:
var express = require('express');
var path = require('path');
var app = express();
app.use('/', function(req, res, next){
console.log(req.path);
}); //ReferenceError: req is not defined
app.use('/', express.static("./public"));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
My understanding is not enough to see why this is an error我的理解不足以看出为什么这是一个错误
In your example, app.use('/', foo(req, res, next));
在您的示例中,
app.use('/', foo(req, res, next));
is calling the function and executing it as it parses through the JS file.正在调用该函数并在它解析 JS 文件时执行它。
The other 'comparison', is a function declaration which isn't called while parsing through the file.另一个“比较”是一个函数声明,在解析文件时不会调用它。
You can change the code to: app.use('/', foo);
您可以将代码更改为:
app.use('/', foo);
and it'll work properly.它会正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.