Home > OS >  Nodejs - Pass variables between functions (Post with Ndeedle)
Nodejs - Pass variables between functions (Post with Ndeedle)

Time:09-18

Im using Needle to do a POST http , then i need to receive back the response ( its some key ) and use it in another POST request.

const needle = require('needle');
const x = needle.post('https://example.com/connect/token' ,
   {
       grant_type: 'password',
       username: 'some_user_name',
       password: 'some_password' , 
       client_id : 'swaggerui',
       client_secret : 'no_password',
   }
   , (err, res) => 
   {
       if (err) 
       {
           console.error(err);
       };
       console.log((res.body).access_token);
   }

);

now I need to get the ((res.body).access_token) into some var and use it again in another POST , how can I achieve that?

CodePudding user response:

There are three approaches to it.

and use it in another POST request.

  1. You put the second POST in the callback of the first request:
const needle = require('needle');
needle.post('https://example.com/connect/token' ,
   {
       grant_type: 'password',
       username: 'some_user_name',
       password: 'some_password' , 
       client_id : 'swaggerui',
       client_secret : 'no_password',
   }
   , (err, res) => 
   {
       if (err) 
       {
           console.error(err);
       };
       else {
           needle.post('<url>', {
               key: res.body.access_token
           });
       }
   }

);
  1. You can define a callback function that makes the second POST with the res.body.access_token passed to it as an argument.
const callback = (access_token) => {
    // ...
    doSomethingWithAccessToken(access_token);
    // ...
}

needle.post('<url>', {
    // ...
}, (err, res) => {
    // ...
    callback(res.body.access_token);
})
  1. You define a global variable and in the callback function you set the value of it to be res.body.access_token
// ...
var access_token = "";
needle.post('<url>', {
    // ...
}, (err, res) => {
    // ...
    access_token = res.body.access_token
});
  • Related