Forked from jmar777/dw-node-http-request-example.js
Last active
August 29, 2015 14:27
-
-
Save 8kigai/980eadac7919bfbf5fa0 to your computer and use it in GitHub Desktop.
Suggested updates to code example on http://davidwalsh.name/nodejs-http-request
This file contains hidden or 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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment