问题描述
我有这个基本功能,可以将消息发送回给我的 Twilio 号码发送消息的用户。
因此,如果号码 1234567890
向我的 twilio 号码发送消息,它会将消息发送回 1234567890
。但是,我希望能够记录用户发送给我的内容。因此,如果他们向我发送 hi
,那么我可以使用它来查询我的数据库并向他们发送消息。
这是我的功能:
app.post('/sms',(req,res) => {
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
res.writeHead(200,{'Content-Type': 'text/xml'});
res.end(twiml.toString());
})
解决方法
这里是 Twilio 开发者布道者。
您似乎正在使用 Node.js 和 Express 来接收来自 Twilio 的传入 Webhook。 When Twilio sends this webhook it includes a number of parameters that describe the message you received。请求以 application/x-www-form-urlencoded
格式发出,因此您需要设置 Express 以解析请求正文中的这些参数。您可以使用内置的 Express urlencoded
middleware:
const express = require('express');
const app = express();
app.use(express.urlencoded());
成功解析请求后,就可以从req.body
中读出参数。例如,发送消息的号码为 req.body.From
,消息正文为 req.body.Body
。例如:
app.post('/sms',(req,res) => {
const { Body,From } = request.body;
console.log(`Message from: ${From}: ${Body}`);
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
res.writeHead(200,{'Content-Type': 'text/xml'});
res.end(twiml.toString());
});