Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

setting up a basic node.js server

setting up a basic node.js server


I am trying to set up a basic node.js server and am getting an error I cannot figure out. I have 4 files: index.js, server.js, router.js, requestHandlers.js


var server = require("./server");
var router = require("./router");
var requestHandlers = ("./requestHandlers");

var handle =  {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);


var http = require('http');
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received"); // 2nd log-- works fine

    route(handle, pathname);

    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write('Hello World');

  console.log("Server has started."); //1st log -- works fine

exports.start = start;


function route(handle, pathname) {
    console.log("About to route a request for " + pathname); //3rd log -- works fine
    console.log(handle); // THIS IS THE PROBLEM returns ---> { '/': undefined, '/start': undefined, '/upload': undefined }
    console.log(pathname); //works fine -- returns "/"
    console.log(typeof handle[pathname]); //undefined
    if (typeof handle[pathname] === 'function') {
        handle[pathname](); //never called because above evaluates to undefined
    else {
        console.log("No request handler found for " + pathname);

exports.route = route;

requestHandlers.js //code never gets here

function start () {
    console.log("Request handler 'start' was called")

function upload () {
    console.log("Request handler 'upload' was called")

exports.start = start;
exports.upload = upload;

I have gone over this 100 times and feel pretty confident about what it's doing, so hopefully there is just some small thing I am missing. thanks!

Problem courtesy of: Nic Meiring


I think you accidentally forgot the verb (require).

var requestHandlers = require("./requestHandlers");
Solution courtesy of: Ignacio Vazquez-Abrams


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

setting up a basic node.js server


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription