简体   繁体   中英

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

I'm trying to have some stuff done before the original app.get is called.

I found this page, I tried what they did and it mostly worked, expect for when I try to use a rendering engine with it.

The code I'm using ( app is the result of express() ):

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 gives me this error: TypeError: View is not a constructor

Does anyone know how I can fix this?

PS: /views/index.ejs does exist

You just need to return original function invocation, otherwise the decorated app.get method is no longer returning anything unlike the original:

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

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