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 trialPrzemyslaw Mazur
Courses Plus Student 9,296 PointsWhy do I have to include an additional statement in the user route ?
I just don't know why the code won't work without this conditional statement request.url.indexOf('.css') === -1 in the user route function.
1 Answer
JASON LEE
17,352 PointsHello.
I can hopefully answer if anyone else had the same question. First this question should be asked in context. I think what you are referring the request.url.indexOf('.css') === -1
in this line here ...
function user(request, response) {
var username = request.url.replace("/", "");
if (username.length > 0 && request.url.indexOf('.css') === -1) {
response.statusCode = 200;
response.setHeader(...commonHeaders);
renderer.view("header", {}, response);
// ...etc.
If you don't include the request.url.indexOf('.css') === -1
, you will get that err STREAM can't write header after it has been set (or something along those lines). WHEN? When the request
for the css file is received, it was already loaded in the previous function commands (not shown here in this snippet) with the header set to "Content-Type" : "text/css"
, and the code will then proceed down to the user function here (with that same .css file request
) and when it reaches the setHeader command line, the error will be thrown.
WHY? Only one response header type per one request. To help illustrate, add console logs of the request.url
and request.method
throughout the start of the functions in router.js, and you will see multiple different "requests" going down the chain of commands.
Other words: The goal is not to have the .css file request
to be executed in this function user
part of the code since it was already loaded previously.
In my opinion, the way the app.js is setup is prone to errors.
const server = http.createServer( (request, response) => {
router.files(request, response)
router.home(request, response);
router.user(request, response);
//for each single "request", the actual response is generally supposed to "do something"
// in only one instance, and skip the rest. But regardless each request goes through ALL the 3 functions.
});