简体   繁体   中英

Node.js code isn't running in javascript function

I'm working with Twilio and sending an example message when the provided code is ran in the terminal:

  var accountSid = '...'; 
  var authToken = '...';  

  var twilio = require('twilio');
  var client = new twilio(accountSid, authToken);

  client.messages.create({
      body: 'Hello World!',
      to: '+1-555-555-5555',  // Text this number
      from: '+18885555555' // From a valid Twilio number
  })
  .then((message) => console.log(message.sid));

However, when I place it in a function to be called on when a button is pressed, then nothing happens.

function messageNow() {
  var accountSid = '...';
  var authToken = '...';

  var twilio = require('twilio');
  var client = new twilio(accountSid, authToken);

  client.messages.create({
      body: 'Hello World!',
      to: '+1-555-555-5555',  // Text this number
      from: '+18885555555' // From a valid Twilio number
  })
  .then((message) => console.log(message.sid));
} 

And call from HTML button:

<button type="submit" id="Btn" class="buttons" onclick="messageNow()">SUBMIT</button>

Any help is appreciated.

Twilio developer evangelist here.

It sounds as though you are trying to run the Twilio Node.js module in the browser. This won't work as the module is only built for server side Node.js, not client side/browser JavaScript.

If you want to send messages via an interface with buttons, you will need to build a web application that can run the Twilio code on the server and present an interface in HTML, CSS and JavaScript that can call the server application.

There are a number of tutorials that take you through different ways you can build apps to send SMS messages with Twilio and Node.js . It might help to take a look there.

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