简体   繁体   中英

Use a class method in router.get

I'm really new to node.js and I'm having trouble when I'm using a class method in router.get callback
It gives me this error:
Can you guys help me out ?

Route.get() requires a callback function but got a [object object]

Here is my code


router.js :

const express = require('express');
const router = express.Router();
const test = require('../controller/controller');
router.get('/', test.testing());
module.exports = router;


controller.js :

class oop
{
    testing(req,res)
    {
        console.log('okay');
    }
}
exports.testing =new oop();


app.js :

const express = require('express');
const app = express();
app.listen(80);
const wiki = require('./routes/router');
app.use('/', wiki);

A callback function will be called in some arbitrary amount of time, therefore you need to provide a reference to the function... so when the time comes, Javascript can execute that function. In your case, you are not passing the function, but running it! test.testing() . What you are actually passing to the 'callback' parameter is the result of test.testing() which, in this case, is undefined

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