Topic: NodeJS Contact Tutorial NOT Functioning Properly

goodfellastech priority asked 1 year ago


I am working on your tutorial for NodeJS contact form. I expect the form to be sent, but the validator returns an error for all fields regardless of if they are blank or not. Also, it appears the HTML code automatically is going to trigger the browser error handing vs. your usual "needs validation" input in the form HTML block.

I have ensured that I copied and pasted all code correctly and checked for all spelling errors and am confused as to why I am getting this error. I was consistently getting a 400 error on the AJAX handle after I fixed the validation to not throw an error for every field every time.

After some research I have noticed that the express validator middleware is wrong. It should read like this for all text fields:

body("field-name).not().isEmpty.withMessage("Message Here")

I am also thinking that in the router or controller there needs to be a data object that is passed in for the ajax handle to work.

Please advise as this tutorial is clearly not working as intended or there is an error in code.


Grzegorz Bujański staff answered 1 year ago


Try this code:

const form = document.getElementById('contact-form');

form.addEventListener('submit', (e) => {
  e.preventDefault();

  const formData = new FormData(form);

  fetch('http://localhost:3000/api/contact', {
      method: 'POST',
      body: formData,
      mode: 'cors'
    })
    .then((response) => response.json())
    .then((response) => {

      // handle errors
      if (response.errors) {
        response.errors.forEach(({ msg }) => {
          document.getElementById('status').innerHTML += `<p class="note note-danger">${msg}</p>`
        });
        return;
      }
      // If mail was sent successfully, reset all elements with attribute 'name'
      const values = document.querySelectorAll('[name]');
      values.forEach( value => {
        value.textContent = '';
      });

      document.getElementById('status').innerHTML = `<p class="note note-success">${response.msg}</p>`;
    })
    .catch((err) => {
      document.getElementById('status').innerHTML += `<p class="note note-danger">${err}</p>`
    })
    .finally(()=> {
      setTimeout(()=> {
        document.getElementById('status').innerHTML = '';
      }, 2000)
    })
});

Grzegorz Bujański staff answered 1 year ago


Is this the tutorial you are talking about?https://mdbootstrap.com/docs/standard/integrations/contact-form-nodejs/


goodfellastech priority commented 1 year ago

Correct. That is what I am referring to.


goodfellastech priority commented 1 year ago

After looking at this and testing a lot of options I keep getting a 400 error when the Ajax call is fetching the route.

I applied the tutorial to a new route on a project I have other working AJAX calls on and it always fails at this code:

fetch('/contact', { method: 'POST', body: formData, mode: 'cors' })

The error that is always kicked back to me is: TypeError: Cannot read properties of undefined (reading 'errors')

I have kept all the validation code, controller code, and route code the exact way as the tutorial. The only difference Is I have my express router go to my contact route which is at "/contact" where the post route is mapped to

router.post("/", validate, (req, res) =>{ const controller = new ContactController(req, res); controller.sendContactForm(); });

When using the inspector I can see the payload, the request chain and everything. It just appears that the specific fetch right there is where the break in the code is.


goodfellastech priority commented 1 year ago

Any update on this? I have searched a lot of things and I keep coming back to getting an Ajax 500 or 400 error. Which means the way the validation is passing data to the route/controller is not correct.

Does this need to be an async/await route so that the validation is completed first and then awaits the ajax handle?



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 6.4.1
  • Device: mac OSX
  • Browser: chrome
  • OS: Ventura
  • Provided sample code: No
  • Provided link: No