Expressjs ejs fn.apply 错误 'View is not a constructor'

Expressjs ejs fn.apply error 'View is not a constructor'

我正在尝试在调用原始 app.get 之前完成一些工作。

我找到了 this 页面,我尝试了他们所做的并且大部分都有效,期待在我尝试使用渲染引擎时使用它。

我使用的代码(appexpress() 的结果):

const express = require('express');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');

var originalfoo = app.get;
app.get = function() {
    // Do stuff before calling function
    console.log(arguments);
    // Call the function as it would have been called normally:
    originalfoo.apply(this, arguments);
    // Run stuff after, here.
};

app.get('/home', function (req, res) {
    //res.send('hello world') // This works
    res.render('index'); // This crashes
});

res.render 给我这个错误:TypeError: View is not a constructor

有谁知道我该如何解决这个问题?

PS:/views/index.ejs确实存在

您只需要 return 原始函数调用,否则装饰后的 app.get 方法不再 returning 任何与原始函数不同的东西:

app.get = function() {
    // Call the function as it would have been called normally:
    return originalfoo.apply(this, arguments);
};