How to Store the Response of a GET Request In a Local Variable In Node JS

后端 未结 1 1628
粉色の甜心
粉色の甜心 2020-12-16 04:40

I know the way to make a GET request to a URL using the request module. Eventually, the code just prints the GET response within the command shell from where it

相关标签:
1条回答
  • 2020-12-16 05:00

    The easiest way (but it has pitfalls--see below) is to move body into the scope of the module.

    var request = require("request");
    var body;
    
    
    request("http://www.stackoverflow.com", function(error, response, data) {
        body = data;
    });
    

    However, this may encourage errors. For example, you might be inclined to put console.log(body) right after the call to request().

    var request = require("request");
    var body;
    
    
    request("http://www.stackoverflow.com", function(error, response, data) {
        body = data;
    });
    
    console.log(body); // THIS WILL NOT WORK!
    

    This will not work because request() is asynchronous, so it returns control before body is set in the callback.

    You might be better served by creating body as an event emitter and subscribing to events.

    var request = require("request");
    var EventEmitter = require("events").EventEmitter;
    var body = new EventEmitter();
    
    
    request("http://www.stackoverflow.com", function(error, response, data) {
        body.data = data;
        body.emit('update');
    });
    
    body.on('update', function () {
        console.log(body.data); // HOORAY! THIS WORKS!
    });
    

    Another option is to switch to using promises.

    0 讨论(0)
提交回复
热议问题