gpt4 book ai didi

javascript - 将路由器与 Express 和 Node.js 结合使用

转载 作者:行者123 更新时间:2023-12-02 15:43:34 24 4
gpt4 key购买 nike

我是 Node.js 新手。我从示例中提取了一些代码,但不知何故我破坏了一些东西:)。

此时,在我的 app.js 文件中,我认为有一行将 Express 与 Node.js 连接起来。该行看起来像这样:

app.js

var routes = require('./routes/index');
// ...
app.get('/', routes.router);

然后,在 ./routes/index.js 中我有以下内容:

routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page */
router.get('/', function(req, res) {
res.send('respond with a resource');
});
module.exports = router;

当我运行此程序时,出现以下错误:

Error: Route.get() requires callback functions but got a [object Undefined]
at Route.(anonymous function) [as get]

我不明白。我做错了什么?

谢谢!

最佳答案

app.js

var routes = require('./routes/index');
//var routes = require('./routes') --> this works
// ...
app.use('/', routes); //Using the router instance as a middleware , relative to '/'

routes/index.js

var express = require('express');
var router = express.Router(); // new instance of Router

/* GET home page */
router.get('/', function(req, res) {
res.send('respond with a resource');
});
module.exports = router; // You export the intance

更新如果您想要超过 1 个路由文件

app.js

var routes = require('./routes')
app
.use("/user",routes.user)
.use("/other",routes.other)

routes/index.js

module.exports = {
user : require(./user),
other : require(./other)
}

routes/user.js

var router = require("express").Router()

router.get("/",function (req,res){
// GET /user
})
.post("/",function (req,res){
//POST /user
})

module.exports = router;

routes/other.js

var router = require("express").Router()

router.get("/",function (req,res){
// GET /other
})
.post("/",function (req,res){
//POST /other
})

module.exports = router;

关于javascript - 将路由器与 Express 和 Node.js 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407552/

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