简体   繁体   English

使用AJAX调用Node.js文件发送短信

[英]Using AJAX to call Node.js file to send SMS message

I'm new to Node.js but I understand that it's on the server-side. 我是Node.js的新手,但我知道它是在服务器端。 When I run my app.js file in Terminal, it sends the text message, but what I'm ultimately trying to do is have the user finish the form, and upon button press, send them a text message to verify their submission. 当我在Terminal中运行app.js文件时,它会发送文本消息,但我最终要做的是让用户完成表单,并在按下按钮时向他们发送文本消息以验证其提交。 I'm using the Twilio service to help accomplish this. 我正在使用Twilio服务来帮助完成此任务。 It's currently not sending a message on button press. 当前在按按钮时不发送消息。

Here's my app.js file: 这是我的app.js文件:

var accountSid = process.env.TWILIO_ACCOUNT_SID;
var authToken = process.env.TWILIO_AUTH_TOKEN;
var client = require('twilio')(accountSid, authToken);

app.get('/testtwilio', function(req, res) {
  client.messages.create({
    to: "+1receivingNumber",
    from: "+myTwilioNumber",
    body: "Testing, testing, testing"
  }, function(err, message) {
    if (err) {
      console.log(err);
    } else {
      console.log(message.sid);
    }
  });
})  

And my Javascript file: 和我的Javascript文件:

$('#buttons').on('click', function(e) {
  $.ajax({
    type: 'POST',
    url: '/testtwilio',
    data: {
      "To": userCellPhone,
      "From": "+1myTwilioNumber",
      "Body": "Ahoy! Testing"
    },
    beforeSend: function(xhr) {
      ...
    },
    success: function(data) {
      console.log(data);
    },
    error: function(data) {
      console.log(data);
    }
  });
});

And lastly, my html button: 最后,我的html按钮:

<button type="submit" id="buttons" class="buttons">SUBMIT</button>

Honestly, I'm not even sure this is possible, but I've been searching forever and can't really find any direct solution. 老实说,我什至不确定这是否可行,但是我一直在搜索,而且真的找不到任何直接的解决方案。 Any help is appreciated! 任何帮助表示赞赏!

Your app variable is undefined. 您的app变量未定义。 If you want to use the express framework like in the tutorials you've followed, you need to register it in your app.js like follows: 如果要像在您所遵循的教程中那样使用express框架,则需要在app.js中注册它,如下所示:

var express = require('express');
var app = express();

Combined with the answers/comments about POST, that should see you on your way. 结合有关POST的答案/评论,您将会在途中看到您。

Nb. Nb。 you'll need to install express in your node modules. 您需要在节点模块中安装Express。 From the command line in your root directory: 从根目录中的命令行:

npm install --save express

nodeJs route expects GET. nodeJs路由期望GET。 But your ajax makes POST request. 但是您的ajax发出POST请求。 Try: 尝试:

app.post('/testtwilio', ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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