[英]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.