简体   繁体   English

Twilio使用Node.js接收和回复SMS

[英]Twilio receive and reply SMS using Node.js

Im trying to set up our twilio app to respond to a client when it receives an sms. 我试图设置我们的twilio应用程序以在收到短信时响应客户端。 I have created a js file that sends out an initial text and another js file that will send the response when it receives a reply. 我创建了一个发送初始文本的js文件和另一个将在收到回复时发送响应的js文件。

I then launched the initial server from my machine then launched ngrok http 1337 I copied and pasted the forwarding url from ngrok into the messaging webhook on my twilio dashboard and added the "/sms" to the end of the url. 然后,我从机器启动了初始服务器,然后启动了ngrok http 1337,我将转发的URL从ngrok复制并粘贴到twilio仪表板上的消息传递Webhook中,并在URL末尾添加了“ / sms”。

When i reply to the text i do not get a response and can see in ngrok that i received a "502 Bad Gateway error". 当我回复文本时,我没有得到任何答复,并且可以在ngrok中看到我收到了“ 502 Bad Gateway错误”。

const accounSid = 'xxxxxxxxxxxxx'
const authToken = 'xxxxxxxxxxxxx'

const client  = require('twilio')(accounSid, authToken)

client.messages.create({
    to: '+13101234567',
    from: '+13109876543',
    body: 'test'
})
.then((message) => {
    console.log(message.sid)
})

const http = require('http')
const express = require('express')

const MessagingResponse = require('twilio').twiml.MessagingResponse

const app = express()

app.post('/sms', (req,res) => {
    const twiml = new MessagingResponse()

    twiml.message('testing 123')

    res.writeHead(200, {'Content-Type': 'text/xml'})
    res.end(twiml.toString())
})

http.createServer(app).listen(1337, () => {
    console.log('express server listening on port 1337')
})

You get 502 Bad Gateway from ngrok because your Express http server is not working or is something wrong with it. 您从ngrok获得502 Bad Gateway ,因为您的Express http服务器无法正常工作或出现问题。

When you respond to SMS, Twilio is making a POST request to your ngrok and that is working because you get that message 502 Bad Gateway on screen. 当您响应SMS时,Twilio正在向您的ngrok发出POST请求,该请求正在工作,因为您在屏幕上看到了502 Bad Gateway消息。

When you launch Express you should see express server listening on port 1337 启动Express时,您应该看到express server listening on port 1337

If you go with your browser to http://localhost:1337/ you should see a page with Cannot GET / since the browser does not make a POST request, but at least you can confirm that the Express server is working. 如果将浏览器转到http://localhost:1337/ ,则应该会看到一个页面,显示Cannot GET /因为浏览器未发出POST请求,但至少可以确认Express服务器正在运行。

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

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