gpt4 book ai didi

node.js - 路由器文件在koa js、nodejs上没有得到返回结果

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:37 24 4
gpt4 key购买 nike

我对 koajs 上的路由器感到困惑,例如有两个文件,一个是主文件app.js,代码如下

//some codes
const home = require("./router/home.js");
router.use("/", home.routes());

另一个是路由器文件home.js,代码如下

router
.get("/:rel", async (ctx) => {
console.log("run sub");
})
.get("/", async (ctx) => {
console.log("run root");
})
module.exports = router;

我以为http://localhost:3000/可以返回控制台日志run root,没错,http://localhost:3000/dlkjf可以返回run sub,但事实并非如此,如果我将home.js更新为

,则没有返回结果
 router
.get("/:rel", async (ctx) => {
console.log("run sub");
})
module.exports = router;

还是一无所知,有什么想法吗?谢谢。

最佳答案

这是关于 module.exports 属性,您在 home.js 末尾设置其值:

module.exports = router;

你应该像这样通过路由器:

module.exports = {router};

或在 app.js 中使用它,如下所示:

const routes = require("./router/home.js");
router.use("/", routes());

关于node.js - 路由器文件在koa js、nodejs上没有得到返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com