coders. I try to implement file upload through Multer. I however get an error trying to catch errors to send to the frontend.
I've tried going through the documentation and the various questions already asked here on Stackoverflow but my understanding of English seems to be so low. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
is my error. I can't find where the headers were sent, or where the process ended. May someone with a better understanding help me out. Here is my code. It happens after the db.query()
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./routes/files");
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage }).fields([
{ name: "file", maxCount: 1 },
{ name: "school_id", maxCount: 1 },
]);
router.post("/upload/students", (req, res) => {
try {
upload(req, res, (err) => {
if (err) {
console.log(err);
res.json({ msg: err.message });
} else {
const filePath = req.files["file"][0].path; //req.file.path;
const workbook = xlsx.readFile(filePath);
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const rows = xlsx.utils.sheet_to_json(worksheet);
const school_id = req.body.school_id;
console.log("SchoolId ", school_id);
rows.forEach((row) => {
const student_id = row.student_id;
const klass_id = row.klass;
const stream_id = row.stream;
const name = row.name;
const year = row.year;
db.query(
"INSERT INTO student(graduated, prefect, school_id,\
name, student_id, klass_id, stream_id, year)\
VALUES($1, $2, $3, $4, $5, $6, $7, $8 )",
[0, 0, school_id, name, student_id, klass_id, stream_id, year],
(err) => {
if (err) {
console.log(err);
// res.json({ msg: err.message });
} else {
console.log("Successfull");
// res.json({ success: "Students Uploaded Successfully" });
}
}
);
});
}
});
} catch (err) {
res.json({ msg: err.message });
}
});
module.exports = router;