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


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
        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) {

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


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");

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

Answered By – yousoumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published