[英]error starting HTTP server in node.js
我正在尝试从index.js页面启动HTTP服务器。 我一直在阅读Node Beginner并按照那里的教程进行操作,但是每次尝试启动HTTP服务器时,都会收到错误消息。 这是代码
Server.js-
var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(10000);
console.log("Server has started.");
}
然后是index.js-
var server = require("./server");
server.start();
但是每次我尝试运行index.js时,都会出现此错误-
server.start();
^
TypeError: Object #<Object> has no method 'start'
at Object.<anonymous> (C:\wamp\www\nodeStack\index.js:2:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
Program exited.
请我如何解决这个问题,谢谢。
var http = require("http");
server.start = function () {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(10000);
console.log("Server has started.");
};
exports.start = start;
您可能会从http://www.nodebeginner.org上的server.js示例代码中监督最后一行。 最后一行是
exports.start = start;
如果将其添加到server.js文件的末尾,一切都应该没问题。
您必须更改server.js以导出启动功能。 您还可以在此处阅读有关module.exports的很好的解释: Node.js module.exports的用途是什么,如何使用它?
var http = require("http");
var server = module.exports = {};
server.start = function () {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(10000);
console.log("Server has started.");
};
我只是遇到了这个确切的问题。 我的解决方法是在index.js中调用server.start时删除()
尝试:
var server = require("./server");
server.start;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.