Nodejs运行但没有输出'Hello'(使用模块)

server.js运行时没有错误信息,仍然在浏览器http:// localhost:1337保持空白,而不是“Hello Node.js”为什么?

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) } } 

你似乎有你的出口倒退。

它是module.exports ,不是module.exports

 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) } } 

另外,hello不会被定义在上下文中,所以你需要在onRequest可以访问的地方定义它。 一个简单的build议重构将导出代码中早先声明的命名函数。

 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 }