【问题标题】:Pass req,res from index.js to another js file in Node将 index.js 中的 req,res 传递给 Node 中的另一个 js 文件
【发布时间】:2021-06-03 05:03:38
【问题描述】:

[我正在为节点使用 express]。

我遇到了一个代码,其中表单数据被发布到index.js,但它必须在另一个 javascript 文件中处理。我几乎在每一步都调试了原始代码,但此时我被卡住了。

这是文件中的相关部分。

index.js

var express = require('express');
var router = express.Router();
const proctor = require('../controllers/proctor');

router.post('/myform', function(req, res, next) {
  console.log("hello");
  proctor.function1;
});
module.exports = router;

proctor.js(不是我写的)

exports.function1 = (req, res) => {
    console.log(req.body);
}

app.js

var indexRouter = require('./server/routes/index');
app.use('/', indexRouter);
module.exports = app;

所以,控制台显示“hello”,但没有显示 req.body,所以第二个 js 文件根本没有被调用。 proctor.js 不是我的代码,我想我需要导入 index.js 才能让它工作。

文件树是

app.js
server
   controllers
      proctor.js
   routes
      index.js

【问题讨论】:

  • 你在哪里调用了function1函数?
  • @Yousaf 已编辑...
  • 你必须使用这个airTicketsController 而不是proctor.function1
  • proctor.function1; - 你的意思是写:proctor.function1(req, res);
  • 尝试添加文件扩展名:'../controllers/proctor.js'

标签: javascript node.js express module.exports


【解决方案1】:

只需像这样用 proctor.function1 替换您的匿名函数

router.post('/myform', proctor.function1);

把监考改成

module.exports = {
  function1: (req, res) => {
    console.log(req.body);
  }
}

【讨论】:

  • 但是出现了Route.post() requires a callback function but got a [object Undefined]的错误
  • 原始代码只是你的建议,但我编辑它删除了这些错误
  • 这个文件存在吗? Console.log 它 - const proctor = require('../controllers/proctor')
  • 是的,这个文件存在并且所有路由都是正确的,因为在这段代码的另一段中,我在proctor.js 中创建了一个数据库连接并在index.js 中查询它并且数据库查询有效。
【解决方案2】:

作为结束问题的象征,因为原始回答者没有添加答案。

  1. const proctor = require('../controllers/proctor'); 导入由proctor.js 文件导出的对象。但是在这种情况下,我们必须使用

    const proctor = require('../controllers/proctor.js');

    能够调用proctor.js中的函数

  2. 我没有将参数传递给函数调用。所以,我不得不这样做

router.post('/myform', function(req, res, next) {
  console.log("hello");
  proctor.function1(req,res,next);
});

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 2014-05-04
    • 2021-02-04
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多