Wednesday 26 April 2017

Why does this client side $.get() request only run the server side code successfully?

I have created a contact form that sends a get request to a route I have hosted locally from a node(express) server. I send the get request when an element is clicked on the dom.

($(document).ready(function () {
  $('#sendEmail').click((e) => {
    e.preventDefault();

    let name = $('#name').val();
    let email = $('#email').val();

    $.get("http://localhost:3000/send", {name: name, email: email})
    .done(() => {
        alert('success!');
    })
    .fail(() => {
        alert('That did not work');
    })
})($)

The node server generates an email based off of information that is gathered from the client. The good news is that the email that is generated works perfectly, and is emailed to my gmail account using nodemailer.

app.get('/send', (req, res) => {
  const mailOptions = {
    name: req.query.name,
    email: req.query.email,
    message: req.query.message,
    to: "",
    from: req.query.name,
    text: ""
  }

  smtpTransport.sendMail(mailOptions, (error, response) => {
    if (error) {
      console.log(error);
      response.end('error');
    } else {
      console.log('Email sent!');
      response.end('sent')
    }
  })
})

Everything is successful server side but no client side code runs after that. Neither my $.done() function or my $.fail() function end up running. What do I need to do so that I can run client side code after the email sends (or doesn't send)?



via Inigo Montoya

No comments:

Post a Comment