2016-08-05 88 views
1

我目前正在使用Express平台,Twilio Node.js SMS API以及明显的JavaScript向我的用户发送短信。问题是,我不知道我应该怎么做才能通过前端的GET变量发送数据,并在后端使用node.js捕获这些值。使用Express从Javascript发送/接收数据到Node.js

出于测试目的,我创建了一个简单的按钮,单击时可将文本消息发送到固定数字。

这里是JavaScript的一面:

function sms() { 
 
    xmlhttp = new XMLHttpRequest(); 
 
    xmlhttp.open("GET","http://localhost:5001", true); 
 
    xmlhttp.onreadystatechange=function(){ 
 
    if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
 
      alert(xmlhttp.responseText); 
 
     } 
 
    } 
 
    xmlhttp.send(); 
 
}

这里是Node.js的一面:

var accountSid = 'ACCOUNT_SID'; 
 
var authToken = 'ACCOUNT_TOKEN'; 
 
//require the Twilio module and create a REST client 
 
var client = require('twilio')(accountSid, authToken); 
 

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

 
app.get('/',function(request,response){ 
 
    
 
    var to = "TO"; 
 
    var from = "FROM"; 
 
    client.messages.create({ 
 
     to: to, 
 
     from: from, 
 
     body: 'Another message from Twilio!', 
 
    }, function (err, message) { 
 
     console.log("message sent"); 
 
     
 
    }); 
 

 
}); 
 
app.listen(5001);

我已经来到ACROS的两个方法可以从Node.js的发送responseText的,但不能设法使他们的工作使用response.send("Hello World"); 第一个或第二个response.write("Hello again"); response.end();

所以只是总结一下,我想送变量(到,来自,消息等)通过我的http请求,捕获它们在node.js并发送responseText!作为一名负责人,我非常喜欢JS和PHP之间的AJAX请求,但Node.js对我来说是新的。

在此先感谢

+0

您提供的代码应该都可以工作,但是您并未在服务器端代码中显示它们。有什么问题?你在哪里把它们放在服务器端代码中?当你提出请求时会发生什么?您是否使用浏览器中的开发人员工具来检查请求?它是否得到了200 OK响应?它是否包含您期望的数据?你是否在控制台中查看错误消息? (我希望看到一个跨源异常,它很容易陷入Google寻找解决方案) – Quentin

+2

一个小纸条,你没有发送任何回到前端通知它的成功。要做到这一点,一个简单的response.send()或response.send('接收数据');会告诉前端200. – Brant

+0

@Quentin当我在浏览器中发出请求时,我得到了200 OK响应,但是当我在JS中评估它时,我无法提醒responseText。控制台日志中没有报警错误消息。 – Felix

回答

0

我认为新指南将帮助你在这里有如何接收和Node.js的回复短信:

https://www.twilio.com/docs/guides/sms/how-to-receive-and-reply-in-node-js

沿着右边的CodeRail会逐步引导您完成,但您应特别注意标题为“生成动态TwiML消息”的部分。

var http = require('http'), 
    express = require('express'), 
    twilio = require('twilio'), 
    bodyParser = require('body-parser'); 

var app = express(); 
app.use(bodyParser.urlencoded({ extended: true })); 

app.post('/', function(req, res) { 
    var twilio = require('twilio'); 
    var twiml = new twilio.TwimlResponse(); 
    if (req.body.Body == 'hello') { 
     twiml.message('Hi!'); 
    } else if(req.body.Body == 'bye') { 
     twiml.message('Goodbye'); 
    } else { 
     twiml.message('No Body param match, Twilio sends this in the request to your server.'); 
    } 
    res.writeHead(200, {'Content-Type': 'text/xml'}); 
    res.end(twiml.toString()); 
}); 

http.createServer(app).listen(1337, function() { 
    console.log("Express server listening on port 1337"); 
});