简体   繁体   中英

Node JS : Route.get() requires a callback function but got a [object Undefined] While using ES6 Modules

Route File

  scoreboardroute.js

  import { scoreRouteController } from '../controllers/scoreboardcontroller';

  const SCOREROUTE = app => {
     app.route('/getAllScores').get(scoreRouteController.getAllScores);
  };

  export { SCOREROUTE };

Controller File

scoreboardcontroller.js
import { scoreBoardModel } from '../model/scoreboardmodel';

class scoreRouteController {

 getAllScores = (req, res) => {
    scoreBoardModel.getAllScoresList((err, response) => {
        if (err) {
            res.send(err);
        }
        res.send(response);
    });
 };
}

export { scoreRouteController };

Model File:

scoreboardmodel.js
import { db } from './db';

class scoreBoardModel {
  getAllScoresList = callback => {
    db.query('Select * from users', (err,response) => {
        callback(err, response);
    });
  }
};

export { scoreBoardModel };

I was trying to use ES6 features like class and arrow functions inside my application. While I'm trying to execute this code it hit the following error. I don't know what went wrong. And I'm really new for node JS server. So, Can anyone please help me to get rid of this error.

Error :

node_modules/express/lib/router/route.js:202 throw new Error(msg); ^

Error: Route.get() requires a callback function but got a [object Undefined] at Route.(anonymous function) [as get] (/node_modules/express/lib/router/route.js:202:15) at SCOREROUTE (/app/routes/scoreboardroute.js:4:32) at Object. (/server.js:26:1) at Module._compile (internal/modules/cjs/loader.js:689:30)

I'm finding the answer.

While importing the class I'm using like Object import. So, changed it like

import scoreRouteController from '../controllers/scoreboardcontroller';

And I'm not going to use so many instances for my application. So, I assign static keyword for my every function inside my class.

static getAllScores = (req, res) => {.....

While exporting I was not exporting an Obj. I changed into default class export.

export default scoreRouteController;

And finally, it works.

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