admin管理员组

文章数量:1355786

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);

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);
Share Improve this question edited Oct 5, 2014 at 23:47 asked Oct 5, 2014 at 20:08 user2272048user2272048
Add a ment  | 

1 Answer 1

Reset to default 5

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
    });
}

本文标签: javascriptMy First Nodejs serverFailed to load resource netERRINCOMPLETECHUNKEDENCODINGStack Overflow