How can I get node-rest-client post data into a useable var

97 Views Asked by At

I have the code:

var client = new Client();
var args = {
    data: { 
        "filters": {
            "uuid": "11111",
            "period": "2018-03-18T00:00:00-05:00/2018-03-21T00:00:00-05:00"
          }
    },
    headers: { 
    "Content-Type": "application/json",
    "Api-User": "myusername",
    "Api-Key": "myapikey"
    }    
};

client.post("https://myAPIenpoint/", args, function (data, response) {
values = JSON.parse(JSON.stringify(data)).id;
console.log(values);
});

console.log(values);

The first console log returns the correct value but the second returns ReferenceError: values is not defined

How can I get values outside of client.post? I know I am probably missing something simple?

1

There are 1 best solutions below

0
On

I don't know if my solution will help You, but i have sth like this:

var EventEmitter = require('events').EventEmitter;
var body = new EventEmitter();

client.post("https://myAPIenpoint/", args, function (data, response) {
    values = JSON.parse(JSON.stringify(data)).id;
    body.data = data;
    body.emit('val');
});

And outside client.post:

 body.on('val', () => {
    let yourDataOutsidePost = body.data;
    console.log(yourDataOutsidePost);
})

I hope it will help.