Emily Mame Ford Emily Mame Ford - 5 months ago 7
Node.js Question

Why won't my node js webserver work for extra pages?

I'm new to Node JS and trying to create my own webserver to host my very basic website on my linux server (Raspberry Pi). The following code displays index.html but it does not display the users.html file. Please point out what I'm doing wrong..I have both the index.html and users.html files in this folder. (Sidenote: I know the CSS & such is not implemented yet; I am only at the beginning of writing this webserver).

var http = require('http');
var fs = require('fs');

//404 response
function send404Response(response){
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404: Page not found!");
response.end();
}

//Handles user request
function onRequest(request, response){
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./index.html").pipe(response);
}else if(request.method == 'Get' && request.url == '/users'){
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./users.html").pipe(response);
}
else{
send404Response(response);
}
}

http.createServer(onRequest).listen(8884);
console.log("Server is running...");

Answer

You have a a type in the second if statement.

else if(request.method == 'Get' && request.url == '/users'){

should instead be

else if(request.method == 'GET' && request.url == '/users'){

HTTP methods are always capitalized, you're server is seeing a "GET" method. The URL doesn't match the first IF statement, and the method doesn't match in the second, so it falls through to the else and gives you a 404 not found.