我在使用Express爲路由和MongoDB(Mongolab)爲數據庫設置Node.js應用程序時遇到問題。我一直在尋找&發現了很多其他用戶有同樣的問題,但無法找到問題的解決方案呢..希望有人可以提供幫助。node.js/express app中的錯誤:發送後無法設置標題
我不斷收到的錯誤是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(route)
/* 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)
我的問題
這個錯誤是什麼意思究竟是什麼問題呢?我怎麼能在這種情況下解決這個問題?
我使用Express作爲路由器和mongoDB作爲數據庫在Node.JS中構建。難道這與它有關嗎?
我提前查了很多類似的問題,#2,但沒能解決我的問題還沒有..
希望有人能幫助我,謝謝!
就想出了一個念頭:
可能的問題是我測試在本地主機上,而MongoDB的(mongolab)被設置在Heroku?
這將有助於瞭解何時出現此錯誤。當你請求'GET /'時你明白了嗎?那麼'GET/login'呢? 'POST /登錄'? –
對不起,忘了提。錯誤發生在'''POST/login'''請求中。索引頁('''res.render('users/index');''')被渲染,但控制檯給出錯誤。會話似乎工作正常,渲染也發生,但仍然得到消息 –
你可能有多個用戶使用相同的用戶名,所以當你找到一個密碼錯誤的時候,它會發送一個響應,但是當你罰款一個使用正確的密碼,它會發送另一個響應。您只能發送1個響應,否則您正嘗試在發送標頭後發送標頭。 –