6

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.

1
  • did you run the file as "node filename.js" ? Commented Nov 13, 2013 at 1:34

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Sorry I didn't notice the date between the tutorial I was using and now, or that the tutorial didn't switch to v10 streams. Thanks.
1

Don't wait for a request-end event. Straight from http://nodejs.org/ with slight modifications:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);

2 Comments

It has, because request is a stream.
Thanks. You are right. Updated answer, although yours is the better one, anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.