刷新后“将标头发送到客户端后无法设置标头”

时间:2019-11-26 22:45:51

标签: node.js express

我正在使用express js,猫鼬和ejs作为模板。

当我刷新页面时,在第二或第三次尝试中,出现此错误。

这是我的app.js:

proc_rollmeans <- function(x) {

  five_yr <- rollmeanr(x, k=5, fill=NA)
  four_yr <- rollmeanr(x, k=4, fill=NA)
  three_yr <- rollmeanr(x, k=3, fill=NA)
  two_yr <- rollmeanr(x, k=2, fill=NA)
  one_yr <- x

  ifelse(!is.na(five_yr), five_yr,
         ifelse(!is.na(four_yr), four_yr,
                ifelse(!is.na(three_yr), three_yr,
                       ifelse(!is.na(two_yr), two_yr, one_yr)
                      )
               )
         )

}

df$var1_five_yr_avg <- with(df, unlist(tapply(var1, id, proc_rollmeans)))

df$var2_five_yr_avg <- with(df, unlist(tapply(var2, id, proc_rollmeans)))

df

#    id start year var1 var2 var1_five_yr_avg var2_five_yr_avg
# 1   1  2005 2000  500  333            500.0        333.00000
# 2   1  2005 2001   10  444            255.0        388.50000
# 3   1  2005 2002   60  555            190.0        444.00000
# 4   1  2005 2003 1000   99            392.5        357.75000
# 5   1  2005 2004   99   15            333.8        289.20000
# 6   1  2005 2005   47    0            243.2        222.60000
# 7   1  2005 2006  180   NA            277.2               NA
# 8   2  2003 2000  -50   NA            -50.0               NA
# 9   2  2003 2001   88   17             19.0         17.00000
# 10  2  2003 2002   13   77             17.0         47.00000
# 11  2  2003 2003  133   55             46.0         49.66667
# 12  2  2003 2004   86   30             54.0         44.75000
# 13  2  2003 2005   10  100             66.0         55.80000

用户路由器:

{consts..}

var index = require('./routes/index.js');
var users = require('./routes/users.js');

app.set("port", ("2401"));
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', index);
app.use('/users', users);

var port = '2401';
app.set('port', port);

var server = http.createServer(app);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  console.log('server started on port : ' + app.get('port'));
}

和控制器:

{consts..}

router.get('/login', function (req, res) {
   users.getLogin(req, res);
});

router.post('/login', [
    check('email')
        .isEmail().withMessage('Please enter a valid email address')
        .trim()
        .normalizeEmail(),
    check('terms', 'Please accept our terms and conditions').equals('yes'),
],
    function (req, res) {
        users.postLogin(req, res);
    });

module.exports = router;

索引路由器:

usersController.getLogin = function (req, res) {
    const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
    mongoose.connection.on('open', function (ref) {
        categories.find(function (err, cats) {
            if (err) {
                console.log("Error:", err);
            }
            else {
                    return res.render("../views/login.ejs", {
                    _: _,
                    categories: cats
                });
            }
        });
    });
}

索引控制器:

var express = require('express');
var router = express.Router();
var index = require("../controllers/indexController.js");

router.get('/', function (req, res) {
  index.list(req, res);
});
module.exports = router;

我尝试了几乎所有内容,但仍然没有任何进展。可以关于“ next()”的用法吗?

我还尝试了下一个孔路由器的get / post函数,并使用exec()来实现猫鼬的查找功能。

1 个答案:

答案 0 :(得分:1)

问题在于您要在每条路线中打开与mongo的连接,并且:

mongoose.connection.on('open'触发过去的请求,已经完成的请求,这就是为什么您得到Cannot set headers after they are sent to the client的原因。

mongoose.connect和侦听器移到每条路由之外。

usersController.getLogin = function (req, res) {

    categories.find(function (err, cats) {
            if (err) {
                console.log("Error:", err);
                return res.status(500).send('error');
            }
            else {
                    return res.render("../views/login.ejs", {
                    _: _,
                    categories: cats
                });
            }
      });

}