Created
November 5, 2014 16:49
-
-
Save jmar777/87fc99cfe3ec27d88e6e to your computer and use it in GitHub Desktop.
Suggested updates to code example on http://davidwalsh.name/nodejs-http-request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} |
@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
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
Hi, isn't the parsed value on line 27 and 28 out of scope?