nodejs express错误:发送后无法设置标头

时间:2017-09-11 13:37:33

标签: javascript node.js express

我正在读取nodejs中不断增长的文件。在我的app.js中使用以下代码。

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

并在下面的html中调用它,

_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...

当我将这个app.js代码放在一个单独的文件(readfile.js)中时,这工作正常但是当我放入app.js时它会出错。

procedure TDSHTTP.PrepareRequest(const ARequest: IHTTPRequest);
var
  LIPRequest: TIPHTTPRequest;
  I: Integer;
  Lprox: TProxySettings;
begin
  if FProxyConnectionInfo <> nil then
  begin
    Lprox := TIPProxyConnectionInfo(FProxyConnectionInfo).FProxySettings;
    //if Lprox.UserName <> emptystr then  // <-- Comment this line out
      FHTTPClient.ProxySettings := TProxySettings.Create(Lprox.Host, Lprox.Port, Lprox.UserName, Lprox.password, Lprox.Scheme);
  end;

请帮助找出错误的位置和要更改的内容。其次,我想在点击按钮时停止此呼叫,我该怎么做?

2 个答案:

答案 0 :(得分:0)

这只是猜测,但是,在app.js中添加代码之前,您是否删除了旧代码?

也许你的/ readfile路由由app.js和单独的文件添加,以便第一个路由发出响应,当第二个路由开始执行相同的操作时,它会收到已经发送的响应错误

答案 1 :(得分:0)

您只能在请求时拨打res.json一次。它设置相关标头,JSON对数据进行编码,将其作为响应发送,然后结束请求。

如果您只想撰写一些数据,可以使用writehttps://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback

或许您可以使用滚轮代替您完成所有工作?

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