我的第一个Node.js服务器:无法加载资源:net :: ERR_INCOMPLETE_CHUNKED_ENCODING

时间:2014-10-05 20:08:42

标签: javascript html node.js single-page-application

以下服务器应该:

案例#1:如果请求为mysitename.html

,请提供http://localhost:8080

案例#2:如果请求是例如,则提供相关文件http://localhost:8080/mysitename.html

CASE#3如果请求为http://localhost:8080/contactform?name=..&..&...etc.

,则会向我发送电子邮件

如果我访问http://localhost:8080/mysitename.html一切正常。加载mysitename.html,然后通过它加载所有后续内容(.js,.css,.png等)。

问题:但是,如果我访问http://localhost:8080,则会发生以下情况:

  • 我在浏览器(Chrome)控制台上收到无法加载资源:net :: ERR_INCOMPLETE_CHUNKED_ENCODING 错误。
  • `mysitename.html'在客户端上显示已损坏。缺少部分DOM,当我尝试查看源页面时,它只是挂起而从未实际加载。仅加载DOM的一部分是奇怪的,因为该文件的所有DOM元素都是静态/硬编码的。
  • 令人困惑的是,其他内容(.js,.css等...)已加载但由于损坏的.html实际上没有显示。 CASE#1是否可能被紧随其后的CASE#2中断?我究竟做错了什么?

CASE#2最初出现错误,导致Johnny Estilles发现无限循环(请参阅下面的答案)。此后已经修复,但现在出现上述问题。

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

1 个答案:

答案 0 :(得分:5)

解决问题#1:无限循环

您在初始if()中错过了等号(或两个)。

更改

if (request.url = "/")

if (request.url == "/")

or 

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

解决问题#2:Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

你错过了案例#1中的response.end()

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