I have Controller which will accept the FormData() from the front-end, but when I am sending the data with Axios it will create the data in mongoDB, but the data is not showing up in the controller, means it is not available as req.body or FormData() in the req, can someone tell me what I am missing?
here is the code Controller:
const contactMiddleware = catchAsync(async (req, res, next) => {
try {
const newContact = await contact.create({
name: req.body.name,
email: req.body.email,
subject: req.body.subject,
text: req.body.text,
});
console.log(newContact, req.body);
res.send('submit successfully');
} catch (error) {
console.log(error);
}
});
Here is the Axios call and the FormData()
const submitContact = async (form_data) => {
try {
const url = 'http://127.0.0.1:8000/api/v1/user/contact/submit';
const response = await axios({
method: 'post',
url,
data: form_data,
headers: { 'Content-Type': 'multipart/form-data' },
});
console.log('x---', response);
if (response.data.status === 'success') {
alert('Signup successfully !!!');
window.location.href = '/user/home';
contactForm.reset();
}
if (response.data.status === 'failed') {
alert('signup attempt failed');
}
} catch (error) {
alert(error.message);
}
};
document.querySelector('.myForm').addEventListener('submit', (e) => {
e.preventDefault();
const form_data = new FormData(contactForm);
form_data.append('name', document.getElementById('name').value);
form_data.append('email', document.getElementById('emailId').value);
form_data.append('subject', document.getElementById('subject').value);
form_data.append('message', document.getElementById('text').value);
// form_data.append('file', document.getElementById('files').files[0]);
console.log(form_data);
submitContact(form_data);
});