node.js - 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函数接受的任何建议。
解决方案
您只需要像这样更改您的应用程序结构:
只需创建一个名为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!
推荐阅读
- c++ - Clang tidy:在表达式末尾添加括号
- reactjs - React Redux thunk - 调度完成后渲染应用程序
- django - Django模型中具有外键的重复值
- python - psycopg2 中的 Python Alter 语句不更新 Peewee
- java - 一个连接中的多个协议
- javascript - JavaScript 中的严格 HTML 解析器
- python - 如何使用轴和子图设置 matplotlib figsize
- javascript - 如何从@google-cloud/storage 读取文件?
- python - 如何避免将多个文件加载到内存中?
- javascript - 需要访问 React Native 中底部选项卡导航器中的状态以实现购物车徽章