2016-08-03 5 views
1

server.jsはエラーメッセージなしで実行されますが、まだブラウザに表示されていますhttp://localhost:1337はなぜ 'Hello Node.js'Nodejsが実行されましたが、モジュールを使用して 'Hello'が出力されませんでした。

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

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

} 

さらに、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 
} 
+0

私はここに次の質問がありますhttp://stackoverflow.com/questions/38753143/this-hello-is-not-a-function-in-nodejs-exports-module – user310291

関連する問題