Separating logic from Express router and still access Express functions Separating logic from Express router and still access Express functions express express

Separating logic from Express router and still access Express functions


req and res are just ordinary objects passed as arguments to the controller function. You don't have to require anything special in Parent.controller.js. Just make sure the parameters for createChild are req, res. And next if you needed. Like so:

module.exports.createChild = (req, res, next) => {   res.status(200).json({ message: 'OK' });}

You will, of course, have to require express in the routes file:

const express = require('express');const Parent = require('Parent.controller');const router = express.Router();Router.post('/create-child', Parent.createChild);


You can wrap all functions in an object and export it like so -

Parent.controller.js

function createChild(req, res, next) {  // do your thing here}// Add more functions// Export modulemodule.exports = {  createChild,  ... // other functions}

Then add it in router like so -

const Parent = require('./Parent.controller.js');Router.post('/create-child', Parent.createChild);

Or you can go the class route -

Parent.controller.js

class Parent {  constructor() {    // fill constructor info  }  createChild(req, res, next) {    // do your thing here  }}module.exports = Parent;

Your router -

const Parent = require('./Parent.controller.js');const parent = new Parent();Router.post('/create-child', parent.createChild);


What exactly have you tried? Accessing req,res should be pretty straightforward,

(module.exports.)createChild = function(req,res){    childName = req.child_name;     ..........    your child genesis code    .....    res.send('Child created')}

As per redirects, you can trigger them with res.redirect(), however, if you want to redirect the user onto an another page, I'd recommend you res.status(307).send or something like that to your front-end which will catch the status code and trigger a window.assign() or something like that.