i have made a route in my express that processes a form when it submits .
i am trying to set a status and send a response to client when the form process faces an error or problem .
i am using FormData() in the front-End and formidable in the back-end .
here is how i am trying to handle errors in the methods call back :
if (err) {
res.status(500) // i have tried different status-codes !
.send(`error on parsing : ${err}`)
.end();
}
the problem is :
1_ if i set most of status codes ( almost all of them except 200 ) then i get an response says Request failed with status code 500 (or other codes i set) and the data sent by .send() method is not received in the client-side
2_ .send() with or without .end() does not stop rest of code to be executed , as i am trying to end response in call backs if they face error , else at the end a 200 status-code is sent , codes execute till end and reach the end and it tries to again set status and i get error cant set headers when they are sent to the client
i have tried to set status code with different methods or send response in other ways .
i searched the web , and i found out the correct way is res.status().send() and i am doing correctly , however i am facing problem .
here is my code (if you need i can paste full code) :
app.post("/upload", (req, res) => {
var form = new formidable.IncomingForm();
form.on("error", err => {
if (err) {
res
.status(500)
.send(`Error on formidable : ${err}`)
.end();
console.log('continued');
}
});
form.encoding = "utf8";
form.uploadDir = "./uploadedFiles/";
form.maxFileSize = 2000 * 1024 * 1024;
form.parse(req, (err, fields, files) => {
if (err) {
res.status(500)
.send(`error on parsing : ${err}`)
.end();
}
// code continues with same style , methods with error handling in call backs
//at the end of code :
res.status(200).send("form successfully Submitted !");
}
"getting response" part of Client-side code :
try {
let response = await axios.post("/upload", FD, {
"Content-Type": "multipart/form-data"
});
console.log(response);
$("#res")
.css("display", "block")
.text(response.data);
$("#spinnerbox").css("display", "none");
} catch (error) {
$("#res")
.css("display", "block")
.text(error);
console.log("Catched Error");
}
i expect when i set a status i be able to send a response as well . ( as i searched res.status().send() should be correct ) .
i would appreciate your helps .