I have an Axios post function that I am using to post multipart form data to a Node.js Express endpoint using Multiparty to process the input fields.
The endpoint receives the data and inserts it in the database. I am trying to use the response status to trigger the form.reset() it all succeeds.
What can I do to get the response status in the post function?
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')
})
}
Endpoint:
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)
})
});
The await in await insertCat(newCategory)
and await res.status(200).json(categories)
were attempts to be sure the insertCat was complete before res.status fired. I’m not really sure if that is the problem. I also tried to use await where the res.status is in the post function. Previously, I was using res.ok
instead of res.status(200)
I suspect the post is not waiting to receive the status. Can I make the post wait?
Thanks for reading
2
Answers
Turns out res.status(200) is not a function, but res.status == 200 in the axios.post function works.
Axios’s
response.status
is not a function.try
res.status === 200
or keepres.ok
instead.