发送后无法设置标头

时间:2015-07-06 08:04:16

标签: javascript node.js express

我曾尝试设置标头,但它不起作用。我已经在每一行的末尾放回。因此,它不应该执行res.json(data)两次。

如果我错了,请纠正我。

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
//var users = require('./routes/users');
var api = require('./routes/api');
var users_page = require('./routes/users_page');
var quizzes = require('./routes/quizzes');
var subjects = require('./routes/subjects');
var questions = require('./routes/questions');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
//app.use('/users', users);
app.use('/api', api);
app.use('/users',users_page);
app.use('/quizzes', quizzes);
app.use('/subjects',subjects);
app.use('/questions',questions);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

users_page.js

var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = process.env.DATABASE_URL || 'postgres://admin:admin@localhost:5432/mydb';

var userHandler = require('./userHandler_post.js'); 
router.post('/', userHandler.post);

var usr2 = require('./userHandler_getusrinfo.js');
router.get('/:username', usr2.getusrinfo);

var usr3 = require('./userHandler_upusr.js');
router.put('/:username', usr3.upusr);


var usr4 = require('./userHandler_del.js');
router.delete('/:username', usr4.del);


var usr5 = require('./userHandler_repasswd.js');
router.put('/reset_password/:username', usr5.repasswd);


var usr6 = require('./userHandler_getall.js');
router.get('/', usr6.get);

module.exports = router;

userHandler_getusrinfo.js:

var pg = require('pg');
var connectionString = process.env.DATABASE_URL || 'postgres://admin:admin@localhost:5432/mydb';

exports.getusrinfo = function(req, res, callback) {

    var username = req.params.username;

  pg.connect(connectionString, function(err, client, done) {
    // Handle Errors
    if(err) {
        res.setHeader('Content-Type', 'application/json');
      res.json(err);
      return ;
    }

        var q2 = client.query("SELECT * FROM dugong.users WHERE UserName =$1 ;",[username]);

        q2.on('error', function(error) {
            var data = {success : false, 
                                    username : username,
                                    reason : {errmsg : error.detail,
                                                        errid : error.code} };  
            res.setHeader('Content-Type', 'application/json');
            res.json(data);
            return callback();
        });    

      q2.on('row', function(row, result) {
          result.addRow(row);
          return ;
      });

      q2.on('end', function(result) {

          if (result.rowCount == 0) {
                    var data = {success : false, 
                                            username : username, 
                                            reason : {errmsg : "Username not found", 
                                                                errid : 'q2'}};
                    res.setHeader('Content-Type', 'application/json');
                    res.json(data);

                    return callback();
                }

                var sumdata = {success: true,
                                        username : result.rows[0].username,
                                        ... //omit to keep it short
                                        FaxNumber : result.rows[0].faxnum
                                        };
          res.setHeader('Content-Type', 'application/json');
          res.json(sumdata);
          return callback();
      });
      done();
      return ;
  });
  pg.end();
};

但是,我收到了这样恼人的消息。 但程序运行正常!

GET /users/Sari 500 45.026 ms - 89
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (/home/sarit/4alls/mariner/node_modules/express/lib/response.js:700:10)
    at ServerResponse.send (/home/sarit/4alls/mariner/node_modules/express/lib/response.js:154:12)
    at fn (/home/sarit/4alls/mariner/node_modules/express/lib/response.js:934:10)
    at View.exports.renderFile [as engine] (/home/sarit/4alls/mariner/node_modules/jade/lib/index.js:374:12)
    at View.render (/home/sarit/4alls/mariner/node_modules/express/lib/view.js:93:8)
    at EventEmitter.app.render (/home/sarit/4alls/mariner/node_modules/express/lib/application.js:566:10)
    at ServerResponse.res.render (/home/sarit/4alls/mariner/node_modules/express/lib/response.js:938:7)
    at /home/sarit/4alls/mariner/app.js:64:7
    at Layer.handle_error (/home/sarit/4alls/mariner/node_modules/express/lib/router/layer.js:58:5)

我是否需要触摸由Express制作的app.js:64:7?如果是这样,我怎么能以正确的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

如果没有更多工作要做或出错,则不应该调用nextApp.js)函数。你的callback文件中有一个catchall(我假设因为你没有发布它),因为你调用nextcallback)函数而被击中。它试图渲染一个错误页面,因此调用Jade渲染。

删除<h:selectOneMenu ... styleClass="hideFirstOption"> 来电。

答案 1 :(得分:-1)

将你的q2查询代码放在其他部分。