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

JavaScript Build a Simple Dynamic Site with Node.js Handling Routes in Node.js Populating User Information

Timo Krämer
Timo Krämer
8,585 Points

Code: Here is the Code without EventEmitter and outsourcing modules. Everything in just one file.

const http = require('http'); const https = require('https');

const hostname = '127.0.0.1'; const port = 3000;

const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); homeVerleitung(req, res); userVerleitung(req, res); });

server.listen(port, hostname, () => { console.log(Server running at http://${hostname}:${port}/); });

function homeVerleitung(request, response) { if (request.url === '/') { response.setHeader('Content-Type', 'text/plain'); response.write('Home Header\n'); response.write('Home Content \n'); response.end('Home Footer\n'); } }

function userVerleitung(request, response) { if (request.url !== '/') { response.setHeader('Content-Type', 'text/plain'); const usedUrl = request.url.replace('/', ''); const userData = getProfile(usedUrl); userData .then((d) => { response.write('User Header\n'); response.write(${d.name}\n); response.end('User Footer\n'); }) .catch((e) => { response.write('Error Header\n'); response.write(e + '\n'); response.end('Error Footer\n'); }); } }

function getProfile(url) { return new Promise((resolve, reject) => { https .get(https://teamtreehouse.com/${url}.json, (res) => { let body = ''; res.on('data', (d) => { body += d.toString(); }); res.on('end', (d) => { try { const jsonBody = JSON.parse(body); resolve(jsonBody); } catch (e) { const error = new Error(We have an Parsing-Error: ${e}); console.log(try..catch Error ${error}); reject(User ${url} is not available); } }); }) .on('error', (e) => { console.log(.on('error') Error ${e}); }); }); }