简体   繁体   English

node.js表达错误:发送标头后无法设置标头

[英]nodejs express Error: Can't set headers after they are sent

I am reading a growing file in nodejs. 我正在用nodejs读取一个不断增长的文件。 Using below code in my app.js. 在我的app.js中使用以下代码。

app.post('/readfile',function (req,res) {   
    var fullfilename = req.body.filepath+"\\"+req.body.filename;
    var bite_size = 256;
    var readbytes = 0;
    var file;

    fs.open(fullfilename, 'r', function(err, fd) {
        file = fd;      
        if(err){console.log(err); throw err; return;};
        var mybuff;
        var func = (function readsome() {               
        var stats = fs.fstatSync(fd); // yes sometimes async does not make sense!
                if(stats.size<readbytes+1) {                    
                    setTimeout(readsome, 1000);
                }
                else {
                    fs.read(fd, new Buffer(bite_size), 0, bite_size, readbytes, function (err, bytecount, buff) {
                    //console.log(buff.toString('utf-8', 0, bytecount));
                    res.json(buff.toString('utf-8', 0, bytecount));
                    readbytes+=bytecount;
                    process.nextTick(readsome);
                    });
                };          
        })();           
    }); 
}); 

And calling this in html like below , 然后像下面这样在html中调用它,

var myApp= angular.module("myApp", [])
myApp.controller('Ctrl1', function ($scope, $http,$q) {
        var FileName = "test.txt"
        var obj = {"filepath" : 'D:\\Temp', "filename" : FileName};

        $http({
                url: '/readTfile',
                method: "POST",
                data: JSON.stringify(obj)
                //timeout: canceller.promise,
                //headers: {'Content-Type': 'application/json','charset' : 'utf-8'}
                }).success(function(result) {               
                $scope.myfiledata = result;                     
                }).error(function(data, status) {
                console.log(data);
                }); 
});

This is working fine when i put this app.js code in a separate file (readfile.js) but when i put in app.js it gives error. 当我将这个app.js代码放在一个单独的文件(readfile.js)中时,此方法工作正常,但是当我将app.js放入它时,它给出了错误。

_http_outgoing.js:357
    throw new Error('Can\'t set headers after they are sent.');
    ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
    at ServerResponse.header (D:\myapp\node_modules\express\lib\response.js:725:10)
    at ServerResponse.send (D:\myapp\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\myapp\node_modules\express\lib\response.js:256:15)
    at D:\myapp\app.js:130:10
    at FSReqWrap.wrapper [as oncomplete] (fs.js:682:17)
[nodemon] app crashed - waiting for file changes before starting...

Please help to find where is the mistake and what to be changed. 请帮助找出错误所在和要更改的内容。 Secondly i want to stop this call on button click, how can i do that ? 其次,我想在单击按钮时停止此呼叫,我该怎么做?

This is just a guess, but, did you remove the old code, before adding the code in app.js ? 这只是一个猜测,但是,在app.js中添加代码之前,您是否删除了旧代码?

Maybe your /readfile route is added by both app.js and in the separate file, so that first route sends out the response, and when the second route starts to do the same, it gets the error of response already been sent. 也许您的/ readfile路由是同时由app.js和在单独的文件中添加的,所以第一个路由发送响应,而当第二个路由开始执行响应时,它会得到已经发送响应的错误。

You can only call res.json once on a request. 您只能在请求中调用一次res.json It sets the relevant headers, JSON encodes the data, sends it as the response and then ends the request. 它设置相关的标头,JSON对数据进行编码,将其作为响应发送,然后结束请求。

If you just want to write some of the data you can use write : https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback 如果您只想写一些数据,可以使用writehttps : //nodejs.org/api/http.html#http_response_write_chunk_encoding_callback

Or maybe you could using piping to do it all for you instead? 也许您可以使用管道系统代替它来完成所有工作?

var readStream = fs.createReadStream(fullfilename);
readStream.pipe(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM