Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
de forbe
76 PointsGET Request not working
const https = require("https");
function getUserData(username) {
let error = "";
let json_data;
try {
const req = https.get(`https://teamtreehouse.com/${username}.json`, res => {
let data = "";
if (res.statusCode == 200) {
res.on("data", in_data => {
data = in_data.toString();
});
res.on("end", () => {
json_data = data
});
} else {
error = `An ${res.statusCode} error occured!`;
}
});
req.on("error", e => {
error = e.message;
})
} catch (e) {
error = e.message;
}
if (error)
return false;
else
return json_data;
}
console.log(getUserData("chalkers"));
Output undefined
1 Answer
de forbe
76 PointsThanks for you answer i got the point is because of that nodejs processes code in async. way. Sir I want to make a function that takes treehouse username as argument and return his/her profile data in the form of json. How can i dot that please help me!
Jim Schofield
11,566 PointsI think you simply need to do your logic inside the block where I placed the comment "this is where the data would be defined".
Another thing you could investigate that might make more sense is using async await
Jim Schofield
11,566 PointsJim Schofield
11,566 PointsI think you're running into the fact that the request takes time. When you run the code, the request is sent and the console log immediately prints out undefined because the data hasn't been processed yet. I'm not exactly sure what you're trying to achieve, but you can look at this: