所以我看到了很多类似我遇到的问题,但是我不明白为什么会这样,所以请帮一个兄弟。
我有一个带有Express + Typescript的简单API,带有两个简单的控制器。 家庭控制器,用于“默认”着陆路线“ localhost:port”。 宠物小精灵控制器,用于在/ pokemon路线下获取宠物小精灵。
所有路由器都导出到index.ts文件中,并导入到server.ts中
home.controller.ts
import { Router, Request, Response } from "express";
const router: Router = Router();
router.get("/", (req: Request, res: Response) => {
res.send("Hi, welcome to my Pokemon Api");
});
export const HomeController: Router = router;
pokemon.controller.ts
import { Router, Request, Response } from "express";
import Pokemon from "../entities/pokemon";
const router: Router = Router();
const pokemons: Pokemon[] = getPokemons(); // Get pokemons from a file/DB, irrelevant
router.get("/", (req: Request, res: Response) => {
if (pokemons !== undefined) {
res.status(200).json(pokemons);
} else {
res.status(500).send("Error retrieving the list of Pokemons");
}
});
export const PokemonController: Router = router;
index.ts
// note the order of these two controllers
export * from "./pokemon.controller";
export * from "./home.controller";
server.ts
import express from "express";
import { HomeController, PokemonController } from "./controllers";
const app: express.Application = express();
const port: number = 3000;
app.use("", HomeController);
app.use("/pokemon", PokemonController);
app.listen(port, () => {
console.log(`Listening at port ${port}`);
});
好的,那么这段代码可以按预期100%运行。 但是,如果在index.ts中切换控制器导出方式的顺序,则会崩溃。 因此,如果我使用的不是上述内容, index.ts
export * from "./home.controller";
export * from "./pokemon.controller";
我收到此错误:TypeError:Router.use()需要一个中间件功能,但未定义。
关于1.为什么会根据顺序发生该问题的任何想法(HomeController中一定有我没有得到的东西,以及2.如何在不切换index.ts导出顺序的情况下解决该问题?
StackTrace:
MYFOLDER\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\app\server.ts:8:5)
at Module._compile (module.js:653:30)
at Module.m._compile (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\node_modules\ts-node\src\index.ts:439:23)
at Module._extensions..js (module.js:664:10)
at Object.require.extensions.(anonymous function) [as .ts] (D:\Mese\Documentos\Proyectos\Pokeapp\PokeApp.api\node_modules\ts-node\src\index.ts:442:12)
at Module.load (module.js:566:32)