#Back-end error (Cannot set headers after they are sent to the client)
18 messages · Page 1 of 1 (latest)
So I have this code, it's nextjs but it's almost the same as if I used just express js
How do I correctly use result here ?
Generally its a good idea to catch an error and do something like res.status(400).json({ error: 'Invalid file type}) for each try block.
But remember throwing an error leads to termination of the function. which means if file type is an important aspect of this handler then it should very much be done before anything else. You are performing a res in middle of the operation but it also has a catch block for it, so despite the error block it will not be able to reach that caught error.
And its better to not nest it inside another try block ( I think your Array.isArray() try block nested inside another try block?). As it would be unable to process the complete request because the nested try and catch will try block the outer one isn't it?
i deleted those unneeded tryblocks
anyway it doesn't work
seems because of form.parse
it doesn't work whenever i use res inside it
Can you share your updated code?
Try not to create too many breaks in your code with errors or returns, create a hierarchy of what should be checked first in your handler. Right now some necessary errors are deep inside the nested blocks. You likely would not want to parse the form data with bad data, so try to first do that check then move to the rest.
case "POST":
const form = new IncomingForm({
multiples: true,
maxFileSize: 50 * 1024 * 1024,
});
form.parse(req, async (err, fields, files) => {
err = "sdfjkasdfkl";
if (err) {
res.status(400).json({ message: "ERROR" });
res.end(String(err));
return;
}
let imagePaths: string[] = [];
const { images }: Files = files;
if (Array.isArray(images)) {
console.log("first");
for (let index = 0; index < images.length; index++) {
const image = images[index];
const isValid = checkFileType(image);
console.log(isValid);
if (!isValid) {
return res.status(400).json({ message: "invalid file type" });
}
const imagePath = saveFile(image);
imagePaths.push(imagePath);
}
} else {
console.log("second");
const isValid = checkFileType(images);
if (!isValid) {
return res.status(400).json({ message: "invalid file type" });
}
saveFile(images);
}
});
// res.status(201).json({ message: "successfully added item" });
break;
i deleted all trycatch blocks
they were just for testing purposes
for some reason it just does not return results from form.parse
why are you setting err output yourself? err = "sdfjkasdfkl";
its supposed to be something returned if there is an error.
err handles error situations to return an error if there is one.
I know
It was just for testig purposes