Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My First Node.js server : Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

The following server is supposed to :

CASE #1 : serve mysitename.html if the request is http://localhost:8080

CASE #2 : serve the relevant file if the request is e.g. http://localhost:8080/mysitename.html

CASE #3 send me an email if the request is http://localhost:8080/contactform?name=..&..&...etc.

If I visit http://localhost:8080/mysitename.htmleverything works fine. mysitename.html is loaded and then all subsequent content (.js, .css, .png etc.) is loaded through it.

PROBLEM : However, if I visit http://localhost:8080, the following happens :

  • I get a Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING error on the browser's (Chrome) console.
  • `mysitename.html' appears corrupted on the client. Parts of the DOM are missing and when I try to view the source page, it just hangs and never actually loads. Loading only part of the DOM is weird given that all DOM elements of this file are static/hardcoded.
  • What's confusing is that the rest of the content (.js, .css etc..) is loaded but nothing actually shows because of the corrupted .html. Is it possible that CASE#1 is interrupted by CASE#2 that follows right after it? What exactly am I doing wrong ?

CASE#2 initially had an error which was causing an infinite loop found by Johnny Estilles (see his answer below). This has since been fixed but the issues mentioned above now occur.

server.js

// setting up email handler
var nodemailer = require('nodemailer');
var emailHandlerService = 'Gmail';
var emailHandlerAddress = ******;
var emailHandlerPassword = ******;
var transporter = nodemailer.createTransport({
    service: emailHandlerService,
    auth: {
        user: emailHandlerAddress,
        pass: emailHandlerPassword
    }
});

// setting up http server
var http = require('http');
var fs = require('fs');
var url = require("url");
var path = require("path");
var rootDir = __dirname + "/public";

var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",

    /* Even though the js mime type is set as well, scripts are still sent 
    as "text/plain" according to the Chrome console. Why is that ? */
    "js": "application/javascript",

    "css": "text/css",
    "ico": "image/ico"
};

// initializing server
var httpServer = http.createServer(function (request, response)
{
    // CASE #1
    // if the user is on http://localhost:8080, load public/mysitename.html
    if (request.url === "/")
    {
        fs.readFile('public/mysitename.html', function (err, html) 
        {
            if (err)
            {
                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.write('404 Not Found\n');
                throw (err);
            }
            else
            {
                response.writeHeader(200, {"Content-Type": "text/html"});  
                response.write(html); 
            }
        });
    }




    // CASE #2
    // else if this is a contact form data request
    // forward the data to my email (I'll make a more precise Regex for the request)

    else if (/contactform/.test(request.url))
    {
        var parsedURL = url.parse(request.url, true);
        var name  = parsedURL.query.name;
        var email  = parsedURL.query.email;
        var subject  = parsedURL.query.subject;
        var enquiry  = parsedURL.query.enquiry;
        var browser = parsedURL.query.browsername + " " + 
                      parsedURL.query.browserversion;

        transporter.sendMail({
            from: emailHandlerAddress,
            to: emailHandlerAddress,
            subject: subject,
            text: "|| NAME = " + name + " || EMAIL = " + 
                   email + " || BROWSER = "  + browser + " || DEVICE = " + 
                   parsedURL.query.device + " || ENQUIRY = " + enquiry
        });

        response.end(JSON.stringify(parsedURL.query));
    }




    // CASE #3
    // if none of the above is true then this is a request to serve static files
    else
    {
        var pathname = url.parse(request.url).pathname;
        var filename = path.join(rootDir, pathname);

        fs.exists(filename, function (exists) 
        {
            if (!exists) 
            {
                fs.readFile('public/404.html', function (err, html) 
                {
                    if (err)
                    {
                        response.writeHead(200, {'Content-Type': 'text/plain'});
                        response.write('404 Not Found\n');
                        throw (err);
                    }
                    else
                    {
                        response.writeHeader(200, {"Content-Type": "text/html"});  
                        response.write(html); 
                    }
                    response.end();
                });
            }
            else
            {
                    var requestedFileExtension = path.extname(filename).split(".")[1];
                var mimeType = mimeTypes[requestedFileExtension] || 'text/plain';

                // as I noted above, this doesn't seem to have any effect 
                // for my .js files
                response.writeHead(200, mimeType);

                var fileStream = fs.createReadStream(filename);
                fileStream.pipe(response);
            }
        });
    }
}).listen(8080);
like image 236
Sprout Coder Avatar asked Oct 05 '14 20:10

Sprout Coder


People also ask

Why is node js not working?

Problems occurring in Node. js application deployments can have a range of symptoms, but can generally be categorized into the following: Uncaught exception or error event in JavaScript code. Excessive memory usage, which may result in an out-of-memory error.

How do I respond to a node JS browser?

setHeader('Content-Type', 'text/html'); this line will set the format of response content o text/html. write() function method on response object can be used to send multiple lines of html code like below. res. write('<html>'); res.


1 Answers

FIXING ISSUE #1: Infinite loop

You're missing an equal sign (or two) in your initial if().

Change

if (request.url = "/")

to

if (request.url == "/")

or 

if (request.url === "/")

FIXING ISSUE #2: Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

Your're missing a response.end() in CASE #1.

// CASE #1
// if the user is on http://localhost:8080, load public/mysitename.html
if (request.url === "/")
{
    fs.readFile('public/mysitename.html', function (err, html) 
    {
        if (err)
        {
            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            throw (err);
        }
        else
        {
            response.writeHeader(200, {"Content-Type": "text/html"});  
            response.write(html); 
        }
        response.end(); // <-- MISSING
    });
}
like image 81
JME Avatar answered Oct 12 '22 00:10

JME