简体   繁体   中英

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:

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:

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)); is calling the function and executing it as it parses through the JS file.

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); and it'll work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM