gpt4 book ai didi

javascript - 使用 Express 从 Javascript 向 Node.js 发送/接收数据

转载 作者:行者123 更新时间:2023-11-28 05:42:45 25 4
gpt4 key购买 nike

我目前正在使用 Express 平台、Twilio Node.js SMS API 和 JavaScript 来向我的用户发送短信。问题是,我不知道应该做什么才能通过前端的 GET 变量发送数据并在后端使用 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);

我遇到了两种从 Node.js 发送响应文本的方法,但无法使它们起作用第一个使用 response.send("Hello World"); 或第二个 response.write("Hello Again");响应.end();

总而言之,我想通过我的http请求发送变量(发件人、发件人、消息等),在node.js中捕获它们并发送responseText!需要注意的是,我对 JS 和 PHP 之间的 AJAX 请求非常满意,但 Node.js 对我来说是新的。

提前致谢

最佳答案

我认为新指南将帮助您了解如何在 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");
});

关于javascript - 使用 Express 从 Javascript 向 Node.js 发送/接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38789276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com