gpt4 book ai didi

javascript - Express 中的路由 Controller 模型存在问题

转载 作者:行者123 更新时间:2023-12-01 00:16:45 25 4
gpt4 key购买 nike

我在为我的路线创建驱动程序时遇到问题。由于某种原因,它无法识别 send() 属性。

这是我的路线代码:

const express = require('express');
const router = express.Router();
const Ctrl = require('../controllers/index');

/* GET home page. */
router.get('/', Ctrl.list());

module.exports = router;

这是我的 Controller 的代码:

const express = require('express');

Ctrl = {}

Ctrl.list = (req, res) => {
res.send("sended");
}

module.exports = Ctrl;

当我使用传统函数(不是箭头函数)时,也会发生同样的情况。

另一方面,这是我的快速配置,其中配置的路由是:

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const helmet = require('helmet');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

const app = express();
require('./database/config');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());

app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;

我收到此错误:

E:\elarchivero\api\controllers\index.js:6 res.send("sended"); ^

TypeError: Cannot read property 'send' of undefined at Object.Ctrl.list (E:\elarchivero\api\controllers\index.js:6:8) at Object. (E:\elarchivero\api\routes\index.js:6:22) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) at Object. (E:\elarchivero\api\app.js:7:21) at Module._compile (internal/modules/cjs/loader.js:959:30) [nodemon] app crashed - waiting for file changes before starting...

最佳答案

您需要将路由器更改为函数引用而不是调用。

router.get('/', Ctrl.list);

关于javascript - Express 中的路由 Controller 模型存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708142/

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