Node.js tutorial web server not responding

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

Code for my server:

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 manual), I get a "No data" message. I have seen several pages that indicate https: //, but this returns an "SSL connection error". I can’t understand what I’m missing.

+6
source share
2 answers

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

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

 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 an HTTP GET handler, you already have all the headers and don't have to wait for the body:

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

Do not wait for the end of the request event. Straight from http://nodejs.org/ with a few changes:

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

Source: https://habr.com/ru/post/957964/


All Articles