0

I'm not quite sure what's going wrong here. It's supposed to return the body of a given webpage; say: example.com as shown here. When called from a separate program like so:

console.log(aux.requestSomething('example.com'))

the result seen in the console is 'undefined', which is the issue, when it should be returning the body from the page.

var request = require('request');
module.exports = {
   requestSomething : function(address){
       var x;
       var v = address;
request(v, function (error, response, body) { //Grabs data from server
   if (!error && response.statusCode == 200) {
    x = body;
  }
  if (error || response.statusCode != 200 ){
    console.log('Network Error ' + response.statusCode + '. Program will exit shortly...');
  }
  return x;
});}}
  • Undefined what? This should be closed. – Marcos Pérez Gude May 24 '16 at 15:57
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Marcos Pérez Gude May 24 '16 at 15:57
  • You need to learn about asynchronous code execution (see the duplicate link). The other issue seems to be a fundamental misunderstanding of functions. Consider the following equivalent but simplified example of your code: `function foo() { function bar() { return 42; } }; foo()`. Notice how `bar` is defined inside `foo` (just like in your code). Notice also that we neither call `bar` inside `foo` itself nor do we return `bar`'s default value. Therefore the `return` statement inside `bar` has no effect on `foo`'s return value. `foo` will always return `undefined`. – Felix Kling May 24 '16 at 16:27

0 Answers0