Search code examples
expressexpress-routermodule.exports

Nodejs how to pass parameters into an exported route from another route?


Suppose I module export "/route1" in route1.js, how would I pass parameters into this route from "/route2" defined in route2.js?

route1.js

module.exports = (app) => {
    app.post('/route1', (req,res)=>{
         console.log(req.body);
    });
}

route2.js

const express = require('express');
const app = express();
//import route1 from route1.js
const r1 = require('./route1')(app);

app.post('/route2', (req, res) => {

   //how to pass parameters?
   app.use(???, r1) ?
})

In short, route 1 output depends on the input from route 2.


Solution

  • You don't pass parameters from one route to another. Each route is a separate client request. http, by itself, is stateless where each request stands on its own.

    If you describe what the actual real-world problem you're trying to solve is, we can help you with some of the various tools there are to use for managing state from one request to the next in http servers. But, we really need to know what the REAL world problem is to know what best to suggest.

    The general tools available are:

    1. Set a cookie as part the first response with some data in the cookie. On the next request sent from that client, the prior cookie will be sent with it so the server can see what that data is.

    2. Create a server-side session object (using express-session, probably) and set some data in the session object. In the 2nd request, you can then access the session object to get that previously set data.

    3. Return the data to the client in the first request and have the client send that data back in the 2nd request either in query string or form fields or custom headers. This would be the truly stateless way of doing things on the server. Any required state is kept in the client.

    Which option results in the best design depends entirely upon what problem you're actually trying to solve.


    FYI, you NEVER embed one route in another like you showed in your question:

    app.post('/route2', (req, res) => {
    
       //how to pass parameters?
       app.use(???, r1) ?
    })
    

    What that would do is to install a new permanent copy of app.use() that's in force for all incoming requests every time your app.post() route was hit. They would accumlate forever.