Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 错误:Can';t将头发送到客户端后设置头_Javascript_Node.js_Express - Fatal编程技术网

Javascript 错误:Can';t将头发送到客户端后设置头

Javascript 错误:Can';t将头发送到客户端后设置头,javascript,node.js,express,Javascript,Node.js,Express,我是Node.js的新手,有一些问题 我正在使用Node.js4.10和express2.4.3 当我尝试访问时,我将被重定向到 然后我收到了以下错误: Error: Can't render headers after they are sent to the client. at ServerResponse.<anonymous> (http.js:573:11) at ServerResponse._renderHeaders (/home/eugene/pu

我是Node.js的新手,有一些问题

我正在使用Node.js4.10和express2.4.3

当我尝试访问时,我将被重定向到

然后我收到了以下错误:

Error: Can't render headers after they are sent to the client.
    at ServerResponse.<anonymous> (http.js:573:11)
    at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25)
    at ServerResponse.writeHead (http.js:813:20)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39)
    at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3)
    at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8)
    at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8)
    at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
    at Array.<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7)
    at EventEmitter._tickCallback (node.js:126:26)

我可以知道我的代码有什么问题吗?

很多人都遇到了这个错误。这与异步处理混淆了。最有可能的是,您的一些代码在第一次勾选中设置了头,然后在以后的勾选中运行异步回调。在这两者之间,会发送响应头,但随后会有更多的头(如30X重定向)尝试添加额外的头,但已经太晚了,因为响应头已经被传输了

我不确定到底是什么原因导致了您的错误,但请将任何回调视为需要调查的潜在区域

简化代码的一个简单提示。摆脱
app.configure()
,只需调用
app。直接在顶级范围内使用


另请参见该模块,它提供Facebook和十几个其他第三方身份验证提供商。

Express中的
res
对象是()的子类。您可以随时调用
res.setHeader(name,value)
,直到调用
res.writeHead(statusCode)
。在
writeHead
之后,头被烘焙,您只能调用
res.write(data)
,最后调用
res.end(data)

错误“error:发送邮件后无法设置邮件头。”表示您已经处于Body或Finished状态,但某些函数试图设置邮件头或statusCode。当您看到此错误时,请尝试查找在某些正文已写入之后尝试发送标头的任何内容。例如,查找意外调用两次的回调,或发送正文后发生的任何错误

在本例中,您调用了
res.redirect()
,这导致响应完成。然后代码抛出了一个错误(
res.req
null
)。由于错误发生在实际的
函数(req,res,next)
(不在回调中),Connect能够捕获它,然后尝试发送一个500错误页面。但是由于已经发送了头,Node.js的
setHeader
抛出了您看到的错误

Node.js/Express响应方法的综合列表以及必须调用它们的时间: 响应必须在头部并保持在头部

  • (仅限特快专递)
  • res.charset='utf-8'
    (仅限Express;仅影响特定于Express的方法)
  • (仅限特快专递)
  • 反应必须在头部并变成身体

  • 响应可以在头部/身体中,也可以在身体中:

  • 响应可以是头部/身体,然后变成完成

  • 响应可以是头部/身体,并保持当前状态:

  • 响应必须在头部并成为已完成

  • 返回下一步([err])
    (仅限Connect/Express)
  • 中间件
    功能(req、res、next)
    中的任何异常(仅限Connect/Express)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)
  • (仅限特快专递)

  • 有一段时间我也遇到了这个错误。我想(希望)我已经把我的头绕在它周围了,想把它写在这里作为参考

    当您使用
    app.use
    方法将中间件添加到或(构建在connect上)时,您将在connect中向
    Server.prototype.stack
    添加项目(至少对于当前的
    npm install connect
    ,这与本文中的github非常不同)。当服务器收到请求时,它会在堆栈上迭代,调用
    (请求、响应、下一步)
    方法

    问题是,如果在一个中间件项中写入响应正文或标题(看起来是/或出于某种原因),但没有调用
    response.end()
    ,并且调用
    next()
    ,那么当核心
    服务器.prototype.handle
    方法完成时,它会注意到:

  • 堆栈中没有其他项,和/或
  • 响应。headerSent
    是真的
  • 所以,它抛出了一个错误。但是它抛出的错误只是这个基本响应(来自connect
    http.js
    源代码:

    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Cannot ' + req.method + ' ' + req.url);
    
    就在这里,它正在调用
    res.setHeader('Content-Type','text/plain');
    ,这可能是您在
    render
    方法中设置的,,而不调用response.end(),类似于:

    response.setHeader("Content-Type", "text/html");
    response.write("<p>Hello World</p>");
    
    response.setHeader(“内容类型”、“文本/html”);
    回答。写(“你好世界”

    ”;
    每件事的结构都是这样的:

    好的中间件
    //不修改响应主体的中间件
    var doesNotModifyBody=函数(请求、响应、下一步){
    request.params={
    a:“b”
    };
    //调用next,因为它尚未修改标头
    next();
    };
    //修改响应主体的中间件
    var doesModifyBody=函数(请求、响应、下一步){
    setHeader(“内容类型”、“文本/html”);
    回答。写(“你好世界”

    ”; response.end(); //不调用next() }; 应用程序使用(不修改正文); 应用程序使用(doesModifyBody);
    有问题的中间件
    var problemMiddleware=函数(请求、响应、下一步){
    setHeader(“内容类型”、“文本/html”);
    回答。写(“你好世界”

    ”; next(); };
    有问题的中间件在不调用
    response.end()
    和调用
    ne的情况下设置响应头
    
    response.setHeader("Content-Type", "text/html");
    response.write("<p>Hello World</p>");
    
    // middleware that does not modify the response body
    var doesNotModifyBody = function(request, response, next) {
      request.params = {
        a: "b"
      };
      // calls next because it hasn't modified the header
      next();
    };
    
    // middleware that modify the response body
    var doesModifyBody = function(request, response, next) {
      response.setHeader("Content-Type", "text/html");
      response.write("<p>Hello World</p>");
      response.end();
      // doesn't call next()
    };
    
    app.use(doesNotModifyBody);
    app.use(doesModifyBody);
    
    var problemMiddleware = function(request, response, next) {
      response.setHeader("Content-Type", "text/html");
      response.write("<p>Hello World</p>");
      next();
    };
    
    app.disable('etag');
    
    auth.annonymousOnly = function(req, res, next) {
        if (req.user) res.redirect('/');
        next();
    };
    
    auth.annonymousOnly = function(req, res, next) {
        if (req.user) return res.redirect('/');
        next();
    };
    
        var error = validateRequestDetails("create",queryReq);
        if (error)
            callback(error, null);
       else
        some code 
        callback(null, success);
    
      var error = validateRequestDetails("create",queryReq);
        if (error)
            callback(error, null);
            return;
        else
           some code 
           callback(null, success);
    
    app.use(function(req,res,next){
      var _send = res.send;
      var sent = false;
      res.send = function(data){
        if(sent) return;
        _send.bind(res)(data);
        sent = true;
    };
      next();
    });
    
    res.send("something response");
    console.log("jhgfjhgsdhgfsdf");
    console.log("sdgsdfhdgfdhgsdf");
    res.send("sopmething response");
    
    router.get('/',function (req,res,next){
         res.send("request received");
         next(); // this will give you the above exception 
    });
    
    app.use(function(req,res,next){
     var _send = res.send;
    var sent = false;
    res.send = function(data){
        if(sent) return;
        _send.bind(res)(data);
        sent = true;
    };
    next();
    });
    
    app.post('/api/route1', function(req, res) {
      console.log('this ran');
      res.status(200).json({ message: 'ok' });
      console.log('this ran too');
      res.status(200).json({ message: 'ok' });
    }
    
    app.get('/api/company/:companyId', function(req, res) {
      const { companyId } = req.params;
      Company.findById(companyId).exec((err, company) => {
          if (err) {
            res.status(500).json(err);
          } else if (!company) {
            res.status(404).json();      // This runs.
          }
          res.status(200).json(company); // This runs as well.
        });
    }
    
    .exec((err, company) => {
      if (err) {
        res.status(500).json(err);
      } else if (!company) {
        res.status(404).json();         // Only this runs.
      } else {
        res.status(200).json(company);
      }
    });
    
    .exec((err, company) => {
      if (err) {
        return res.status(500).json(err);
      } else if (!company) {
        return res.status(404).json();  // Only this runs.
      }
      return res.status(200).json(company);
    });
    
    article.save(function(err, doc1) {
      if (err) {
        res.send(err);
      } else {
        User.findOneAndUpdate({ _id: req.user._id }, { $push: { article: doc._id } })
        .exec(function(err, doc2) {
          if (err) res.send(err);
          else     res.json(doc2);  // Will be called second.
        })
    
        res.json(doc1);             // Will be called first.
      }
    });
    
    WebSocket.on("message", (data) => {
        receivedMessage = true;
        doSomething(data);
        localSocket.close(); //This close the connection, allowing 
    });
    
    module.exports = (req,res,next)=>{
            try{
               const decoded  = jwt.verify(req.body.token,"secret");
               req.userData = decoded;
               next();
            }catch(error){
                return res.status(401).json({message:'Auth failed'});
            }
            next();   
            }
    
    switch (status) {
        case -1:
          res.send(400);
        case 0:
          res.send(200);
        default:
          res.send(500);
    }
    
    switch (status) {
        case -1:
          res.send(400);
          break;
        case 0:
          res.send(200);
          break;
        default:
          res.send(500);
          break;
    }
    
    userModel.createUser(data, function(err, data) {
        if(err) {
          res.status = 422
          res.json(err)
          return // without this return the error can happen.
        }
        return res.json(data)
      })
    
    if(condition A)
    { 
    
          res.render('Profile', {client:client_});
    
    }
    
    if (condition B){
    
          res.render('Profile', {client:client_});
        }
      }
    
          const dataExistsInterval = setInterval(async () => {
            const dataExists = Object.keys(req.body).length !== 0;
            if (dataExists) {
              if (!req.files.length) {
                return res.json({ msg: false });
              } else {
                  clearInterval(dataExistsInterval);
                try {
                . . .
    
    var mongoose = require('mongoose');
    // set Promise provider to bluebird
    mongoose.Promise = require('bluebird');
    
    // q
    mongoose.Promise = require('q').Promise;