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

元气小坏坏 提交于 2019-12-18 04:17:10

问题


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 has been spawned.

How do I store these GET response in a local variable so that I can use it else where in the program?

This is the code i use:

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

回答1:


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.



来源:https://stackoverflow.com/questions/30485756/how-to-store-the-response-of-a-get-request-in-a-local-variable-in-node-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!