简体   繁体   中英

Execute externally $ node hello.js from within a javascript function?

I'm a very beginner backend developer, so my apologies if this question is rather novice. For a certain javascript file, the script performs perfectly when I execute it using

$ node hello.js

However, I wish to execute this javascript code through a button click on my form. Encapsulating this code into a function and calling the function seems to result in an error every single time.

tls.connect is not a function

Is there a way to manually reproduce the terminal command $ node hello.js from javascript? Any solutions or helpful links would be greatly appreciated. For some context, the code in question is meant to forward an email with a message to a single recipient when activated. I am using nodemailer to achieve this alongside a server hosted on DigitalOcean. The webapp is built using React.

sendMyMail(event) {
  var nodemailer = require('nodemailer');
  var smtpTransport = require('nodemailer-smtp-transport');

  let transporter = nodemailer.createTransport(smtpTransport({
    service: 'gmail',
    secure: false,
    port: 25,
    auth: {
      user: 'myemail@gmail.com',
      pass: 'mypass'
    },
    tls: {
      rejectUnauthorized: false
    }
  }));

  let HelperOptions = {
    from: '"Contact Form" <myemail@gmail.com',
    to: 'myforward@gmail.com',
    subject: 'Hello World',
    text: 'Hello World 2.0'
  };



  transporter.sendMail(HelperOptions, (error, info) => {
    if (error) {
      console.log("Unable to send mail!");

      return console.log(error);
    }
    console.log("The message was sent!");
    console.log(info);
  });

}

You will need a node server in order to send an email via the script you wrote. The script must be invoked in order to send the mail. In order to invoke that particular script, you'll need a server that will serve that script when route (which handles the script invocation) is encountered.

For details, see: https://appdividend.com/2017/08/11/send-email-in-node-js/#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM