访问发件人 phone 号码 twilio Node.js webhook

Access sender phone number twilio Node.js webhook

为了在用户回复 Twilio 消息时做出响应,Twilio 会向您指定的服务器发出 post 请求。如何从 post 请求参数中访问发件人 phone 号码?我希望以后能够向他们发送 Twilio 消息。

示例代码

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('The Robots are coming! Head for the hills!');

    // is it 
    // req.params.From
    // ? 
    // that's giving me undefined

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

http.createServer(app).listen(8080, () => {
    console.log('Express server listening on port 8080');
});

docs 说此信息在“post 请求参数”中给出,但就像我在示例代码中指出的那样,req.params.From 为我返回未定义。

这里是 Twilio 开发人员布道师。

来自 phone 的号码和其他参数在 post 请求的正文中作为表单编码参数 (application/x-www-form-urlencoded) 发送。全部 the request parameters are listed in the documentation.

要阅读它们,您需要使用 Express 的 urlencoded middleware 解析请求正文(您可以通过调用 app.use(express.urlencoded()); 为您的应用程序设置它)然后您将能够从 req.body.From.

读取参数
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();
app.use(express.urlencoded());

app.post('/sms', (req, res) => {
    const twiml = new MessagingResponse();
    twiml.message('The Robots are coming! Head for the hills!');

    console.log(req.body.From);

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

http.createServer(app).listen(8080, () => {
    console.log('Express server listening on port 8080');
});