我有一个显示 HTML 文档(包括 .jpg 图像)的代码和一个创建新的 .txt 文件、将数据保存到其中并在控制台中显示的代码。
但每次我用谷歌浏览器运行这段代码时,数据都会显示 3 次...
代码
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
//branje HTML datoteke
var file_path = '.' + request.url;
if (file_path == './')
file_path = './func.html';
var extname = path.extname(file_path);
var contentType = 'text/html';
switch (extname) {
case '.jpg':
contentType = 'image/jpg';
break;
}
fs.readFile(file_path, function (error, content) {
if (error) {
if (error.code == 'ENOENT') {
fs.readFile('./404.html', function (error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Server error!: ' + error.code + ' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
fs.writeFile("external-data.txt", "- TEXTFILE-CONTENT\n", function (err) {
if (err) {
return console.log(err);
}
console.log("Data saved!\n");
});
fs.readFile(__dirname + '//external-data.txt', function (err, data) {
console.log(data.toString());
response.end(data);
});
结果
有什么建议吗?代码有什么问题,为什么它多次显示相同的文本而不是一次?谢谢!
最佳答案
在 Chrome 中打开开发者工具。查看“网络”选项卡。提出请求。
您会看到 Chrome 发出多个请求。例如,对于 /favicon.ico
。
每个请求都会触发您的代码。
关于javascript - 为什么 node.js 会多次显示相同的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36037540/