Skip to content
Advertisement

Pass req,res from index.js to another js file in Node

[I am using express for node].

I encountered a code where the form-data is being posted into index.js but it has to be processed in another javascript file. I debugged the original code at nearly every step but at this point I am stuck.

Here are the relevant parts in the files.

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 (not written by me)

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

app.js

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

So, console shows “hello”, but not the req.body so the second js file is not being called at all. The proctor.js is not my code and I think I need to import index.js maybe to get it working.

The file tree is

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

Advertisement

Answer

As a token of closing the question, since the original answerer is not adding the answer.

  1. const proctor = require('../controllers/proctor'); imports the object exported by the proctor.js file. But in this case, we have to use

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

    to be able to call the functions present in proctor.js

  2. I was not passing the arguments to the function call. So, I would have to do

router.post('/myform', function(req, res, next) {
  console.log("hello");
  proctor.function1(req,res,next);
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement