server.js 运行时没有错误消息,仍在浏览器中 http://localhost:1337保持空白而不是“Hello Node.js”,为什么?
服务器.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);
你好.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
,不是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)
}
}
此外,hello 不会在该上下文中定义,因此您需要在 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
}
关于javascript - Nodejs运行但没有输出 'Hello'(使用模块),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38752538/