将 req,res 从 index.js 传递到 Node 中的另一个 js 文件

问题描述

[我正在为节点使用 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

解决方法

像这样用 proctor.function1 替换你的匿名函数

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

将监考人员更改为

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

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

  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,next);
});