我曾尝试设置标头,但它不起作用。我已经在每行末尾添加了return。因此,它不应两次执行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吗?如果是这样,我该怎么做呢?

最佳答案

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

关于javascript - 发送后无法设置标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31240626/

10-09 19:37