Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:\github\V2\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\github\V2\node_modules\express\lib\response.js:174:12)
at C:\github\V2\app\API\register.js:84:13
at C:\github\V2\node_modules\mongodb\lib\utils.js:371:9
at C:\github\V2\node_modules\mongodb\lib\cursor\abstract_cursor.js:260:32
at C:\github\V2\node_modules\mongodb\lib\cursor\abstract_cursor.js:510:55
at C:\github\V2\node_modules\mongodb\lib\utils.js:371:9
at C:\github\V2\node_modules\mongodb\lib\sessions.js:136:24 {
code: 'ERR_HTTP_HEADERS_SENT'
This is the code in my file that is causing the problem.
const express = require('express');
const app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb srv://web:U*****[email protected]/";
const cookisSession = require('cookie-session');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongodbsession = require('connect-mongodb-session')(session);
const cookieParser = require('cookie-parser');
const { response } = require('../database');
app.use(bodyParser.urlencoded({ extended: false })); // เรียกใช้งาน body-parser
app.use(session({
secret: 'Session-service',
resave: false, // ต้องการบันทึกค่าหรือไม่
saveUninitialized: false, // ต้องการบันทึกค่าหรือไม่
maxAge: 1000 * 60 * 60 * 24 * 7, // กำหนดระยะเวลาการเปิดตัวคุณภาพการเชื่อมต่อกับคอมพิวเตอร์
store: new mongodbsession({
uri: 'mongodb srv://web:U******[email protected]/',
dbName: 'webjs',
collection: 'sessions'
})
}));
app.post('/a-login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
// เข้ารหัส password
const hash = require('crypto').createHash('sha256');
hash.update(password);
const password_hash = hash.digest('hex');
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("webjs");
dbo.collection("users").find({ name: username, password: password_hash }).toArray(function(err, result) {
if (err) throw err;
if (result. Length > 0) {
res.send("ยินดีต้อนรับคุณ " username);
} else {
res.send("ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
}
db.close();
} );
} );
if (result.length > 0) {
// บันทึกค่าลง session
req.session.username = username;
req.session.gemd = result[0].gemd;
req.session.email = result[0].email;
req.session.id = result[0]._id;
req.session.save();
} else {
res.send("ไม่สมารถเข้าสู่ระบบได้");
}
} );
module. Exports = app;
How should I fix this problem?
This text was translated by google.
CodePudding user response:
You can't modify the session (as it'd send a header) after you've res.send()
ed some content.
Additionally, since the Mongo connection stuff is async, you can't have an if
after that block and expect it to work correctly.
Something like the following might be closer to what you want, but I would recommend refactoring things to use async
/await
. Also, absolutely don't use sha256 for password hashing.
app.post("/a-login", (req, res) => {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
const { username, password } = req.body;
// เข้ารหัส password
const hash = require("crypto").createHash("sha256");
hash.update(password);
const password_hash = hash.digest("hex");
db.db("webjs")
.collection("users")
.find({ name: username, password: password_hash })
.toArray(function (err, result) {
if (err) throw err;
if (result.length > 0) {
// บันทึกค่าลง session
req.session.username = username;
req.session.gemd = result[0].gemd;
req.session.email = result[0].email;
req.session.id = result[0]._id;
req.session.save();
res.send("ยินดีต้อนรับคุณ " username);
} else {
res.send("ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
}
db.close();
});
});
});