0

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

index.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);

server.js

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');
    response.end();
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started."); //1st log -- works fine

};
exports.start = start;

router.js

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!

1
  • i commented in the code where the error is. my object properties are coming back as undefined Commented Apr 2, 2012 at 16:36

1 Answer 1

7

I think you accidentally forgot the verb (require).

var requestHandlers = require("./requestHandlers");
Sign up to request clarification or add additional context in comments.

1 Comment

hey sorry. when it was originally answered, it was too soon to mark as correct. Marked it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.