Skip to content

Instantly share code, notes, and snippets.

@jmar777
Created November 5, 2014 16:49
Show Gist options
  • Save jmar777/87fc99cfe3ec27d88e6e to your computer and use it in GitHub Desktop.
Save jmar777/87fc99cfe3ec27d88e6e to your computer and use it in GitHub Desktop.
Suggested updates to code example on http://davidwalsh.name/nodejs-http-request
function getTestPersonaLoginCredentials(cb) {
http.get({
host: 'personatestuser.org',
path: '/email'
}, function(res) {
// explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
res.setEncoding('utf8');
// incrementally capture the incoming response body
var body = '';
res.on('data', function(d) {
body += d;
});
// do whatever we want with the response once it's done
res.on('end', function() {
try {
var parsed = JSON.parse(body);
} catch (err) {
console.error('Unable to parse response as JSON', err);
return cb(err);
}
// pass the relevant data back to the callback
cb(null, {
email: parsed.email,
password: parsed.pass
});
});
}).on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
cb(err);
});
}
@joshy
Copy link

joshy commented Apr 22, 2015

Hi, isn't the parsed value on line 27 and 28 out of scope?

@styfle
Copy link

styfle commented Jun 2, 2015

@irrwitz No it is not because var declarations are hoisted to the top of the function. There is a lot of examples online if you search such as Mozilla docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

@datamaskin
Copy link

Since this is a function obviously this won't work at the node command-line. Do you have an example of howto see this work @ the node command-line?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment