在快递上发送标题后无法设置标题

时间:2014-12-26 15:38:19

标签: javascript node.js express mean

我在这里表达了一个常见的问题。但我无法从各地获得解决方案。 这是我的代码:如果row不为空,则渲染代码页,否则执行另一个操作。

app.get('/send',function(req,res){
  var code=req.query['c']; // -- get request from input
  connection.query("use mynum");
  var strQuery = "select * from table WHERE code='"+code+"' LIMIT 1";   
  connection.query( strQuery, function(err, rows){
    if(err) {
      throw err;
    }else{
      if(rows.length==1){
        res.render('pages/code', {code : rows[0].code});
        connection.end();
        res.end();
      }else {
        // here is some actions
      }
    }
  });
  res.end();
});

堆栈跟踪:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
at ServerResponse.header (C:\wamp\www\vin_number\node_modules\express\lib\re
sponse.js:666:10)
at ServerResponse.res.contentType.res.type (C:\wamp\www\vin_number\node_modu
les\express\lib\response.js:532:15)
at ServerResponse.send (C:\wamp\www\vin_number\node_modules\express\lib\resp
onse.js:121:14)
at fn (C:\wamp\www\vin_number\node_modules\express\lib\response.js:900:10)
at View.exports.renderFile [as engine] (C:\wamp\www\vin_number\node_modules\
ejs\lib\ejs.js:323:3)
at View.render (C:\wamp\www\vin_number\node_modules\express\lib\view.js:93:8
)
at EventEmitter.app.render (C:\wamp\www\vin_number\node_modules\express\lib\
application.js:530:10)
at ServerResponse.res.render (C:\wamp\www\vin_number\node_modules\express\li
b\response.js:904:7)
at Query._callback (C:\wamp\www\vin_number\server.js:102:6)

2 个答案:

答案 0 :(得分:7)

您通过res.end()两次发送回复。摆脱第二个,你应该没事。此外,在res.end()之后调用res.render()是多余的,因为默认情况下res.render()会自动以渲染结果结束响应。

答案 1 :(得分:0)

刚学会了这个!通过检查响应是否已发送的函数传递您的回复:

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