我有一个应用程序,该应用程序允许用户通过将电话号码输入输入字段来发送文本消息。但是短信设置为"你好"。我该如何允许用户输入他们想要的短信说的话。这是代码
JS
app.get("/:data", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: "Hello"
}, function(err, message) {
if(err) {
console.log(err);
} else {
console.log(message.sid);
}
});
html
<input type="text" placeholder="Enter your number" id="inputNum" />
<button id="submitNum">Enter</button>
<script>
submitNum.addEventListener("click", function(){
var inputNum = document.getElementById("inputNum");
var submitNum = document.getElementById("submitNum");
var phoneNumber = inputNum.value;
fetch(" https://*******************.com/"
+ phoneNumber).then((resp)=>{
console.log(resp);
});
});
twilio开发人员在这里。
要允许您的用户输入消息,您需要在HTML表单中添加额外的字段,然后将该字段添加到API请求中。我还建议不要将电话号码添加到URL的路径中,而是将电话号码添加到查询参数。因此,先拿到您的HTML,我将其更改为:
<input type="text" placeholder="Enter your number" id="inputNum" />
<textarea name="inputMessage" id="inputMessage"></textarea>
<button id="submitNum">Enter</button>
<script>
var inputNum = document.getElementById("inputNum");
var inputMessage = document.getElementById("inputMessage");
var submitNum = document.getElementById("submitNum");
submitNum.addEventListener("click", function(){
var phoneNumber = inputNum.value;
var message = inputMessage.value;
var query = "phoneNumnber=" + encodeURIComponent(phoneNumber);
query += "&message=" + encodeURIComponent(message);
fetch(" https://*******************.com/sendMessage?" + query).then((resp)=>{
console.log(resp);
});
});
</script>
然后,您需要更新服务器以使用消息变量和sendMessage
端点。我还建议您回复回复,以免您的前端悬挂。这样:
app.get("/sendMessage", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: req.params.message
}, function(err, message) {
if(err) {
console.log(err);
resp.setStatus(200).send();
} else {
console.log(message.sid);
resp.setStatus(500).send();
}
});
});
让我知道这是否有帮助。