Sai Ashwin Sai Ashwin - 4 months ago 9
Node.js Question

Node.js code does not execute

I have written some Node.js code but when I run

node index.js
in my terminal it's just blank. My Node script does not even log to the console after creating the server or is responding with my
index.html
file. I even tried changing all 'req' and 'res' to 'request' and 'response'. Here's my code:



var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({ extended: false });

http.createServer(function(request, response){
console.log('listening on port 8080');
app.on('request', function(request, response){
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function(request, response){
var user = request.body.user;
var pass = request.body.pass;
});
}).listen(8080);





Pleas help. Thanks in advance.

EDIT: Anything inside the
http.createserver();
does not execute because I tried logging another sentence outside the
http.createServer();
and it logged!

Answer

Go ahead and try the following:

var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({extended: false});

app.on('request', function (request, response) {
    response.sendFile('./index.html');
});
app.post('/auth', urlparse, function (request, response) {
    var user = request.body.user;
    var pass = request.body.pass;
});

// Bind createServer with app:
http.createServer(app).listen(8080, function (request, response) {
    console.log('listening on port 8080');
});

I expect that this should work for you.

Update:

The method mentioned, while works, has become outdated. the recommended method is:

app.listen(8080, function () {
    console.log('listening on port 8080');
});

Using this method allows you to skip requiring http.

Comments