【问题标题】:Why does node.js display same content multiple times?为什么 node.js 会多次显示相同的内容?
【发布时间】:2016-03-16 22:28:01
【问题描述】:

我有一个显示 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);
});

结果

有什么建议吗?代码有什么问题,为什么它多次而不是一次显示相同的文本?谢谢!

【问题讨论】:

  • 请求 html 页面,请求图片,请求 favicon... 生成 3 个文件。您应该记录他们请求的网址。
  • 我的案例有什么例子吗? @Bergi

标签: javascript node.js


【解决方案1】:

在 Chrome 中打开开发者工具。查看网络选项卡。提出请求。

您将看到 Chrome 发出 多个 请求。例如,对于/favicon.ico

每个请求都会触发您的代码。

【讨论】:

  • 要么什么都不做,要么更加关注浏览器的请求并采取相应的行动。
  • 我不知道你的意思是什么:(
  • 检查 req 对象。查看请求的内容。根据请求做不同的事情。
  • 我做了不同的事情,但如果我不请求 jpg 图像,它就不会显示在页面上。我得到的只是假设是图像的空白窗口,但它不是......
  • @fox:我们并不是说您不应该请求图片,而是您应该只在请求特定 URL 时调用 fs.writeFile("external-data.txt", …)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多