2016-08-03 33 views
1

server.js沒有錯誤消息運行時,仍然在瀏覽器http://localhost:1337留空白,而不是「你好的Node.js」爲什麼?運行的NodeJS但沒有輸出「你好」(模塊使用)

server.js:

var hello = require('./hello'); 

var http = require('http'); 
var ipaddress = '127.0.0.1'; 
var port = 1337; 

var server = http.createServer(hello.onRequest); 
server.listen(port, ipaddress); 

hello.js:

exports.module = { 

    hello: function (req, res) { 
     res.end('Hello Node.js'); 
    } 
    , 
    onRequest: function (req, res) { 
     res.writeHead(200, {'Content-Type': 'text/plain'}); 
     hello (req, res) 
    } 

} 
+2

and ...'hello(req,res)'不會引發錯誤?啊,*,因爲它永遠不會被調用。* –

回答

3

你似乎有你的出口倒退。

module.exports,不exports.module

module.exports = { 

    hello: function (req, res) { 
     res.end('Hello Node.js'); 
    }, 
    onRequest: function (req, res) { 
     res.writeHead(200, {'Content-Type': 'text/plain'}); 
     hello (req, res) 
    } 

} 

此外,你好不會在這方面規定,所以不是,你需要的地方定義它在那裏onRequest可以訪問它。一個簡單的建議重構將是出口早些時候在代碼中聲明命名函數。

function hello(req, res) { 
    res.end('Hello Node.js'); 
} 

function onRequest(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    hello(req, res) 
} 

module.exports = { 
    hello: hello, 
    onRequest: onRequest 
} 
+0

我這裏有一個問題,以後http://stackoverflow.com/questions/38753143/this-hello-is-not-a-function-in-nodejs-exports-module – user310291