2016-11-15 84 views
4

我刚刚用自制软件安装了node.js(v7.1.0)和npm(3.10.9),我试图运行一个基本的web服务器。Node.js找不到基本功能

编辑*我现在实例化调度,但仍然得到同样的错误


var http = require('http'); 
var port = 8080; 
var HttpDispatcher = require('httpdispatcher'); 
var http   = require('http'); 
var dispatcher  = new HttpDispatcher(); 

dispatcher.setStaticDirname(__dirname); 
dispatcher.setStatic(''); 

dispatcher.onGet("/page1", function (req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    res.end('Page One'); 
}); 

var server = http.createServer().listen(port); 


server.on('request', function (req, res) { 
    console.log('GOT'); 
    dispatcher.dispatch(req, res); 
}); 

当我运行该命令节server.js我得到这个错误

dispatcher.setStaticDirname(__dirname); 

TypeError: dispatcher.setStaticDirname is not a function 
    at Object.<anonymous> (/Users/NodeJS/node_modules/server.js:5:12) 
    at Module._compile (module.js:573:32) 
    at Object.Module._extensions..js (module.js:582:10) 
    at Module.load (module.js:490:32) 
    at tryModuleLoad (module.js:449:12) 
    at Function.Module._load (module.js:441:3) 
    at Module.runMain (module.js:607:10) 
    at run (bootstrap_node.js:420:7) 
    at startup (bootstrap_node.js:139:9) 
    at bootstrap_node.js:535:3 

对于dispatcher.onGet调用,我得到同样的错误。

+1

你是否在你的package.json上添加了'httpdispatcher'并运行'npm install'? – Enrichman

+0

我运行命令'npm install httpdispatcher',仍然得到相同的错误 –

回答

8

您没有正确使用httpdispatcher。您必须在使用它之前实例化调度程序。

var HttpDispatcher = require('httpdispatcher'); 
var dispatcher  = new HttpDispatcher(); 

编辑:我设置一个working example on webpackbin。该代码位于main.js。您可以在log选项卡上查看输出。

+0

多余的行似乎并不重要我得到相同的错误 –

+0

根据这个库的文档,你必须这样做 – Florent

+0

只为澄清,每当你得到一个TypeError,根据httpdispatcher文档[here](https://www.npmjs),知道你正试图调用一个不属于你正在使用的Type的方法(函数)。 com/package/httpdispatcher),您必须先拥有httpdispatcher init的实例,然后才能设置setStatic和onGet。 –