12

suppose I have a simple express js application like the following:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  return res.json({ hello: 'world' });
});

module.exports = app;

I want to be able to go to the command line, require the app, start the server and simulate a request. Something like this:

var app = require('./app');
app.listen(3000);
app.dispatch('/') // => {hello:"world"}
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
brielov
  • 1,887
  • 20
  • 28

4 Answers4

11

You can use run-middleware module exactly for that. This is working by creating new Request & Response objects, and call your app using those objects.

app.runMiddleware('/yourNewRoutePath',{query:{param1:'value'}},function(responseCode,body,headers){
     // Your code here
})

More info:

Disclosure: I am the maintainer & first developer of this module.

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
3

this solution works perfectly by using express 4.16 (and optionally -express promise router , which is great wrapper for error handling)

its straightforward, without using router inside a router nor re-write the request, like in the other suggested answers

just change the URL in the request and return it to router handle function

const router = require('express-promise-router')();

router.post('/signin', function(req, res , next) {

    if (req.body.Username === 'admin') {
        req.url = '/admin/signin'   
        router.handle(req, res, next)
    }
    else  {  // default doctor
        req.url = '/doctors/signin'
        router.handle(req, res, next)
    }

});

router.post('/doctors/signin',someCallback1)
router.post('/admin/signin',someCallback1)
Ron87k
  • 139
  • 1
  • 5
3

These two options worked for me without any error:

option 1

app.post('/one/route', (req, res, next) => {
  req.url = '/another/route'
  req.method = 'GET'
  next();
});

app.get('/another/route', (req, res) => {
  console.log("Hi, I am another route");
});

option 2

app.post('/one/route', (req, res, next) => {
  req.url = '/another/route'
  req.method = 'GET'
  app._router.handle(req, res, next);
});

app.get('/another/route', (req, res) => {
  console.log("Hi, I am another route");
});
  • Express : 4.15.4
  • No extra library or npm module is required
JRichardsz
  • 14,356
  • 6
  • 59
  • 94
-1

As far as I am aware, there isn't a way to switch to a specific route internally, but there is a way to flag the request, then move on to the next route:

app.use((req, res, next) => {
    if("nextRouteCondition"){
        req.skip = true;
        return next();
    }
})

This may allow you to accomplish what you want to do.

Adam Fowler
  • 1,750
  • 1
  • 17
  • 18