Emily Mame Ford Emily Mame Ford - 1 year ago 35
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!");

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

console.log("Server is running...");

Answer Source

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.