javascript 我的第一个 Node.js 服务器:无法加载资源:net::ERR_INCOMPLETE_CHUNKED_ENCODING
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26206719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
My First Node.js server : Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
提问by Sprout Coder
The following server is supposed to :
以下服务器应该:
CASE #1 : serve mysitename.html
if the request is http://localhost:8080
案例#1:mysitename.html
如果请求是http://localhost:8080
CASE #2 : serve the relevant file if the request is e.g. http://localhost:8080/mysitename.html
案例#2:如果请求是例如,则提供相关文件 http://localhost:8080/mysitename.html
CASE #3 send me an email if the request is http://localhost:8080/contactform?name=..&..&...etc.
案例 #3 如果请求是,请给我发送电子邮件 http://localhost:8080/contactform?name=..&..&...etc.
If I visit http://localhost:8080/mysitename.html
everything works fine. mysitename.html
is loaded and then all subsequent content (.js, .css, .png etc.) is loaded through it.
如果我访问http://localhost:8080/mysitename.html
一切正常。mysitename.html
加载然后所有后续内容(.js、.css、.png 等)通过它加载。
PROBLEM :However, if I visit http://localhost:8080
, the following happens :
问题:但是,如果我访问,则会http://localhost:8080
发生以下情况:
- I get a Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODINGerror 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 ?
- 我在浏览器 (Chrome) 控制台上收到无法加载资源:net::ERR_INCOMPLETE_CHUNKED_ENCODING错误。
- `mysitename.html' 在客户端上显示已损坏。DOM 的一部分丢失了,当我尝试查看源页面时,它只是挂起而从未真正加载。鉴于此文件的所有 DOM 元素都是静态/硬编码的,因此仅加载 DOM 的一部分很奇怪。
- 令人困惑的是,其余的内容(.js、.css 等)已加载,但由于 .html 损坏,实际上没有显示任何内容。CASE#1 是否有可能被紧随其后的 CASE#2 中断?我到底做错了什么?
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.
CASE#2 最初有一个错误,导致 Johnny Estilles 发现无限循环(见下面他的回答)。此问题已得到修复,但现在出现了上述问题。
server.js
服务器.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);
回答by JME
FIXING ISSUE #1: Infinite loop
修复问题 #1:无限循环
You're missing an equal sign (or two) in your initial if()
.
您的初始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
修复问题#2: Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
Your're missing a response.end()
in CASE #1.
你response.end()
在案例#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
});
}