Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a route handler manually in express js?

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"}
like image 633
brielov Avatar asked Mar 10 '15 15:03

brielov


People also ask

How do I redirect Route Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

What is a route handler in Express?

Handler is a callback function that executes when a matching request type is found on the relevant route. For example, var express = require('express'); var app = express(); app.

How does routing work in Express js?

Routing with Express in Node: Express. js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function, which is called when a request is received.

How can we create route handlers for a route path in Express js app?

You can create chainable route handlers for a route path by using app. route() . Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.


1 Answers

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:

  • Module page in Github & NPM;
  • Examples of use run-middleware module

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

like image 176
Aminadav Glickshtein Avatar answered Sep 23 '22 09:09

Aminadav Glickshtein