My current task involves utilizing an Axios post function to send multipart form data to a Node.js Express endpoint using Multiparty for input field processing.
Upon receiving the data, the endpoint saves it in the database. I am looking to utilize the response status to trigger a form.reset() upon successful completion.
How can I retrieve the response status within the post function?
Here is the code snippet for the listener and post:
let categories = []
const form = document.getElementById("category");
const formEvent = form.addEventListener("submit", async (event) => {
event.preventDefault();
let cat = new FormData(form);
cat.append('userId',userId)
await postCat(cat);
});
const postCat = async (cat) =>{
await axios.post('http://localhost:8080/api/category-api/addNew/?',
cat, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then( (res) => {
if ( res.status(200)){
form.reset();
document.getElementById('shim').style.display = document.getElementById('msgbx').style.display = "none";
}
else if (!res.status(200)) {
return null
}
})
.catch((e) => {
console.log('ERROR ERROR', e, 'ERROR ERROR')
})
}
This section pertains to the endpoint setup:
router.post("/addNew/", async (req, res) => {
let form = new multiparty.Form();
let pros = [], cons = [];
let newCategory = { pros, cons }
await form.parse(req, async (err, fields) => {
await Object.keys(fields).forEach((property) => {
if (fields[property].toString().length > 0 && fields[property].toString() !== ' ') {
if (property.startsWith('pro')) newCategory.pros.push(fields[property].toString())
else if (property.startsWith('con')) newCategory.cons.push(fields[property].toString())
else newCategory[property] = fields[property].toString();
}
if (property === ('name') && newCategory[property].length === 0) {
return res.status(400).json({ msg: "Name must be included" });
}
}
)
categories.push(newCategory) //inside form.parse is the key!
await insertCat(newCategory)
await res.status(200).json(categories)
})
});
I have tried using await insertCat(newCategory)
and
await res.status(200).json(categories)
to ensure that insertCat completes before triggering res.status. However, it seems like the post method does not wait for the status. Is there a way to make it wait?
Thank you for your attention.