首页 > 解决方案 > Route.get() 需要一个回调函数,但得到一个 [object Undefined]

问题描述

我的应用程序在带有打字稿的 nodejs 中。我试图分离路由,并引入接口和控制器来执行后面的逻辑。

应用程序.ts

const countryRoutes = require('./routes/countryroute')
app.use('/countries', countryRoutes)

countryRoute.ts

var countryuController = require('./../controller/country/countrycontroller')
var express = require('express')
var router = express.Router()

router.get('/getValidCountry', countryController.validCountry)
module.exports = router

ICountryController.ts

interface ICountryController {
    validCountry(req: any, res: any)
}

CountryController.ts

class CountryController {
    constructor() {}
    validCountry(req: any, res: any) {
        //application Logic here
    }
}

module.exports = CountryController

在countryRoute.ts之前一切正常,但之后控件不会转到countryController.ts,它会给出以下错误

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

我尝试改变在控制器文件中编写方法的方式,但我得到了同样的异常。我也尝试过其他问题的解决方案,但没有一个对我有用。

关于如何在类文件中编写函数以供.get函数接受的任何建议。

标签: node.jstypescriptrouter

解决方案


您只需要像这样更改您的应用程序结构:

只需创建一个名为routes.ts的文件,然后在其中定义函数

var countryuController = require('./../controller/country/countrycontroller');

module.export = (app) => {
  app.get("/getValidCountry" , countryController.validCountry);
}

并在你的app.ts中使用路由,如下所示:

const app = express();
const routes = require("./routes");

routes(app);

通过这种方式,您也可以链接多个控制器:D!


推荐阅读