I am trying to make a simple server responding to url / page1 and / page 2; This is the dispatcher.js module:
var HttpDispatcher = function() { this.listeners = { get: [ ], post: [ ] }; this.errorListener = function() { } } HttpDispatcher.prototype.on = function(method, url, cb) { this.listeners[method].push({ cb: cb, url: url }); } HttpDispatcher.prototype.onGet = function(url, cb) { this.on('get', url, cb); } HttpDispatcher.prototype.onPost = function(url, cb) { this.on('post', url, cb); } HttpDispatcher.prototype.onError = function(cb) { this.errorListener = cb; } HttpDispatcher.prototype.dispatch = function(req, res) { var parsedUrl = require('url').parse(req.url, true); var method = req.method.toLowerCase(); if(this.listener[method][parsedUrl.pathname]) this.listener[method][parsedUrl.pathname](req, res) else this.errorListener(req, res); } module.exports = new HttpDispatcher();
and this is the server:
var dispatcher = require('./node_modules/httpdispatcher'); var http = require('http'); dispatcher.onGet("/page1", function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Page One'); }); dispatcher.onPost("/page2", function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Page Two'); }); http.createServer(function (req, res) { dispatcher.dispatch(req, res); }).listen(80, '127.0.0.1');
But when I try to execute the server, I get an error:
D: \ Works \ Web Resources \ NODE JS \ node_modules \ httpdispatcher.js: 33
if (this.listener [method] [parsedUrl.pathname]) this.listener [method] [parsedUr ^ TypeError: Cannot read the 'get' property from undefined
Does anyone know why?
source share