Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not read property '/' of undefined

I started studying node.js. I ask you questions while studying. when I run my code(server) and connect to localhost, It doesn't work properly.

This is error: enter image description here

This is my code:

index.js

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

var handle = {};
handle['/'] = requestHandlers.view;
handle['/view'] = requestHandlers.view;
handle['/create'] = requestHandlers.create;

server.start(router.route, requestHandlers.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('\nrequest for ' + pathname + ' received.');

      response.writeHead(200, {'Content-Type' : 'text/plain'});
      // route(handle, pathname); // injected function call
      var content = route(handle, pathname);

      response.write(content);
      response.end();
    }

  http.createServer(onRequest).listen(8000);

  console.log('server has started.');
}

exports.start = start;

router.js

function route(handle, pathname) {
    console.log('about to route a request for ' + pathname);
    if (typeof handle[pathname] === 'function') {
        return handle[pathname]();
    } else {
        console.log('no request handler found for ' + pathname);
        return "404 Not found";
    }
}

exports.route = route;

requestHandlers.js

function view(response) {
    console.log('request handler called --> view');
    return "Hello View";
}

function create(response) {
    console.log('request handler called --> create');
    return "Hello Create";
}

exports.view = view;
exports.create = create;
like image 534
Selena Lee Avatar asked Dec 20 '25 15:12

Selena Lee


1 Answers

In index.js, you're passing requestHandlers.handle, which doesn't exist, rather than the handle object that you've created.

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

var handle = {};
handle['/'] = requestHandlers.view;
handle['/view'] = requestHandlers.view;
handle['/create'] = requestHandlers.create;

// server.start(router.route, requestHandlers.handle);
server.start(router.route, handle);
like image 132
Joe Clay Avatar answered Dec 23 '25 03:12

Joe Clay