使用node.js和express在Twilio中请求undefined

时间:2017-04-20 21:20:44

标签: node.js twilio

我创建了一个回复Twilio语音电话的webhook。

var router = require('express').Router();
var twilio = require('twilio');

router.post("/voice", (request, response) => {
  // var fs = require('fs');
  // var util = require('util');
  // fs.writeFileSync('./request.json', util.inspect(request.body), 'utf-8');
  console.log(request.body);
  console.log('Call received from ' + request.body.From);
  //twimlAnswer();}

webhook和连接工作正常,但我试图访问Twilio通常提供的一些请求参数,请求' (与此示例类似https://www.twilio.com/docs/tutorials/automated-survey-node-express#responding-to-a-phone-call

我收到以下日志:

Express server listening on port 3000
undefined
TypeError: Cannot read property 'From' of undefined
    at router.post

您知道为什么我没有正确访问请求吗?我发现的大多数示例都没有访问request.body ...

的问题

谢谢,

1 个答案:

答案 0 :(得分:2)

Twilio开发者传道者在这里。

Twilio sends webhook requests as URL encoded form parameters。因此,要在Express中读取请求主体,您需要包含Body Parser模块并将应用程序设置为使用urlencoded解析器。有点像这样:

var router = require('express').Router();
var twilio = require('twilio');
var bodyParser = require('body-parser');

router.use(bodyParser.urlencoded({ extended: false }));

router.post("/voice", (request, response) => {
  console.log('Call received from ' + request.body.From);
  // respond to webhook
});