2016-11-15 64 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。 –