Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js tutorial web server not responding

I was viewing this post while trying to get started Node.js, and I started working with this guide to learn the basics.

The code for my server is :

var http = require('http');

http.createServer(function (request, response) {
    request.on('end', function() {
        response.writeHead(200, {
            'Content-Type' : 'text/plain'
        });
        response.end('Hello HTTP!');
    });
}).listen(8080);

When I go to localhost:8080 (per the guide), I get a 'No Data Received' error. I've seen some pages that say https:// are required, but that returns a 'SSL Connection Error'. I can't figure out what I'm missing.

like image 395
Blex Avatar asked Nov 13 '13 01:11

Blex


1 Answers

The problem in your code is that "end" event is never fired because you are using Stream2 request stream as if it's Stream1. Read migration tutorial - http://blog.nodejs.org/2012/12/20/streams2/

To convert it to "old mode stream behavior" you can add "data" event handler or '.resume()' call:

var http = require('http');

http.createServer(function (request, response) {
    request.resume();
    request.on('end', function() {

        response.writeHead(200, {
            'Content-Type' : 'text/plain'
        });
        response.end('Hello HTTP!');
    });
}).listen(8080);

If your example is http GET handler you already have all headers and don't need to wait for body:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {
    'Content-Type' : 'text/plain'
  });
  response.end('Hello HTTP!');
}).listen(8080);
like image 80
Andrey Sidorov Avatar answered Oct 07 '22 20:10

Andrey Sidorov