Node.js Express - app.all ("*", func) is not called when visiting the root domain

I am trying to set a global function that is called every time the page loads, regardless of its location on my website. According to the Express API, I used

app.all("*", doSomething);

to call the doSomething function every time the page loads, but it does not work completely. The function works every time the page is loaded, with the exception of loading the pages of the base domain (for example, http://domain.com/pageA is called by the function, but http://domain.com will not). Does anyone know what I'm doing wrong?

Thanks!

+4
source share
5

, , -.

, :

app.use(express.static(path.join(__dirname, 'public')));

var router = express.Router();

router.use(function (req, res, next) {
    console.log("middleware");
    next();
});

router.get('/', function(req, res) {
    console.log('root');
});
router.get('/anything', function(req, res) {
   console.log('any other path');
});

, /

, express.static public/index.html /

, :

app.use(express.static(path.join(__dirname, 'public'), {
    index: false
}));
+4

,

app.get('/', fn)

app.all("*", doSomething);

, Express , , -

+2

, .

, :

app.use(function(req, res, next){
  //whatever you put here will be executed
  //on each request

  next();  // BE SURE TO CALL next() !!
});

,

+1

Where is app.all ('*') in the chain? If it is after all other routes it cannot be called.

app.post("/something",function(req,res,next){ ...dothings.... res.send(200); });

app.all('*',function(req,res) { ...this NEVER gets called. No next and res already sent });

If it was your intention to be the last, then you should definitely call next () in the previous routes. For example:

app.post("/something",function(req,res,next){ ...dothings.... next();});

app.all('*',function(req,res) { ...this gets called });

Also, what's in doSomething? Are you sure you didn’t call him?

+1
source

I also had this problem, and I found that the number of arguments to your function doSomethingcan be a factor.

function doSomething(req, res, next) {
    console.log('this will work');
}

then:

function doSomething(req, res, next, myOwnArgument) {
    console.log('this will never work');
}
0
source

All Articles