Asma_Kh
Asma_Kh

Reputation: 93

How transfer data between post requests with Nodejs

I have to send data from one post request to another post request in the same server so How can i send my results information from app.post('/convert') to app.post('/last') ?

Here are my post requests :

   app.post('/convert',  upload.single('file'), (req, res) => {

                let var1='asma'; 
       let  var2='hello ';

       let results={

        first:var1,

       others:var2
       }


        })


       })


app.post('/last', upload.single('file'),(req, res) =>{
        console.log(var1);
        console.log(var2);
        res.send(results);
 });

How can I use var1 and var2 in the second app.post ?

Upvotes: 1

Views: 795

Answers (2)

ippi
ippi

Reputation: 10177

I'll assume for a second that you actually don't want to make a new post-request and just want to know how to create and use middleware.

function convert(req,res,next){
  req.var1 = "hello";
  req.var2 = "world";
  next();
};

function last(req,res){
    console.log(req.var1);
    console.log(req.var2);
    res.send(results);
}

app.post('/doPlenty', [upload.single('file'), convert], last});

Did I assume too much?

Upvotes: 3

Orelsanpls
Orelsanpls

Reputation: 23545

You have to keep a reference of the variables in a higher level.

The following example is showing to you a very simple method :

let referenceOnVar1 = false;
let referenceOnVar2 = false;

function func1() {
  const var1 = 'asma';
  const var2 = 'hello ';
  
  referenceOnVar1 = var1;
  referenceOnVar2 = var2;

  const results = {
    first: var1,
    others: var2,
  };
}


function func2() {
  console.log(referenceOnVar1);
  console.log(referenceOnVar2);
}

func1();
func2();

Upvotes: 2

Related Questions