Home > database >  How to pass the flow control from a router to another function?
How to pass the flow control from a router to another function?

Time:08-26

In index.js I have:

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

const { codeExecute } = require('../controllers/userController');

router.get('/', function(req, res, next) {
    if (req.query.code){    // if there is "code" param in the get request
        console.log(req.query.code)    // here it correctly prints if there is "code" in the request
        codeExecute(req,res,next)    // here I'd like to pass the flow control to this function
    }else{
        res.render('index', { title: 'La mia Home Page' });
    }
});

In userController.js I have:

async function codeExecute(req, res, next) {

    try {
        console.log(req.body.code)    // this prints undefined
        //do stuff, for example res.render something

    } catch (err) {
        console.log(err);
        next(createError(500));
    }
}

Can I pass the flow control to another function that will render inside a router?

CodePudding user response:

You can call next() at this specific line where you wanna delegate the request to codeExecute after adding it as third parameter, like so:

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

const { codeExecute } = require("../controllers/userController");

router.get(
  "/",
  function (req, res, next) {
    if (req.query.code) {
      console.log(req.query.code);
      next(); // pass to codeExecute
    } else {
      res.render("index", { title: "La mia Home Page" });
    }
  },
  codeExecute
);
  • Related