繁体   English   中英

node.js / express应用程序中的错误:发送标头后无法设置标头

[英]Error in node.js/express app: Can't set headers after they are sent

我在通过Express设置Node.js应用程序以进行路由而在数据库中使用MongoDB(Mongolab)时遇到了问题。 我一直在环顾四周,发现许多其他用户都遇到相同的问题,但仍未找到解决问题的方法。希望有人能提供帮助。

我一直收到的Error: Can't set headers after they are sent.Error: Can't set headers after they are sent.

POST /login请求后出现错误。 我试图使用res.end(); res.redirect('/users/index'); 并返回渲染。.但是还没有成功..

这里最重要的代码:

Server.js

  /* LOAD ALL DEPENDENCIES
    ----------------------------------------- */
    const express = require('express');
    const path = require('path');
    const request = require('request');
    const session = require('express-session');
    const compression = require('compression');
    const bodyParser = require('body-parser');
    const app = express();

    /* MONGODB CONFIGURATION
    ----------------------------------------- */
    const MongoClient = require("mongodb").MongoClient;
    require('dotenv').config();
    const dbConfig = process.env.MONGODB_URI;

    MongoClient.connect(dbConfig, (err, database) => {
      if (err) return console.log(err)
      db = database
    });

    /* SESSIONS CONFIGURATION
    ----------------------------------------- */
    app.use(session({
        secret: "JA1d82JHYF9?nsdfDF635MuHe#ksd",
        resave: false,
        saveUninitialized: true
    }));

    /* SET PORT FOR HEROKU
    ----------------------------------------- */
    const port = process.env.PORT || 3000;
    const host = process.env.HOST ||'0.0.0.0';

    // Rest of the code ..

    app.use('/users', usersRouter);
    // Router is loaded earlier

    /* START THE NPM SERVER
    ----------------------------------------- */
    app.listen(port, host, function() {
        console.log(`Server started on port ${port}`);
    });

users.js(路由)

/* LOAD ALL DEPENDENCIES
----------------------------------------- */
const express = require('express');
const router = express.Router();
const passwordHash = require('password-hash');

/* INDEX ROUTE
----------------------------------------- */
router.get('/', function(req, res) {
  if (req.session.login) {
    res.render('users/index');
  } else {
    res.redirect('/users/login');
  }
});

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

router.post('/login', function(req, res) {
  const loginName = req.body.username;
  const loginPassword = req.body.password;
  db.collection('users').find().toArray(function(err, results) {
    results.map(function(user) {
      if (user['username'] === loginName) {
        const pwCheck = passwordHash.verify(loginPassword, user['password']);
        if(pwCheck === true) {
          req.session.login = true;
          req.session.username = user['username'];
          res.render('users/index');
        } else {
          res.redirect('/users/')
        }
      }
    })
  });
});

完全错误

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:725:10)
    at ServerResponse.send (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:170:12)
    at done (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:962:10)
    at tryHandleCache (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:208:10)
    at View.exports.renderFile [as engine] (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:412:10)
    at View.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/view.js:128:8)
    at tryRender (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:640:10)
    at EventEmitter.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:966:7)

我的问题

该错误的确切含义是什么,出了什么问题? 在这种情况下,我该如何解决?

我在Node.JS中构建,其中Express作为路由器,而mongoDB作为数据库。 可能与这有关吗?

我在Stackoverflow上检查了很多类似的问题,但是还不能解决我的问题。

希望有人能帮助我,在此先感谢!

刚想到:

问题可能是我在localhost上测试,而mongodb(mongolab)在Heroku上设置了吗?

您的问题是,对于数据库查询返回的每个与密码和用户名匹配的结果值,您都在调用res.render() 每个请求只能调用res.render() 因此,从理论上讲,如果仅返回1个用户并且其密码匹配,这将起作用,但是如果同一用户多次存在并且具有相同的密码,则在发送一次之后将调用res.render()

我的建议是遍历返回的用户列表,然后在首次匹配后细分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM