user310291
user310291

Reputation: 38180

Nodejs runs but did not output 'Hello' (using module)

server.js runs with no error message, still in the browser http://localhost:1337 stays blank instead of 'Hello Node.js' why ?

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

}

Upvotes: 1

Views: 54

Answers (1)

Brandon Anzaldi
Brandon Anzaldi

Reputation: 7270

You seem to have your export backwards.

It's module.exports, not 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)
    }

}

In addition, hello won't be defined in that context, so instead, you'll need to define it somewhere where onRequest can access it. A simple suggested refactoring would be exporting named functions declared earlier in the code.

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
}

Upvotes: 3

Related Questions