Reputation: 67
I created a webhook answering Twilio voice calls.
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();}
The webhook and the connection work fine, but I am trying to access some of the request parameters usually provided by Twilio inside 'request' (similar way than this example https://www.twilio.com/docs/tutorials/automated-survey-node-express#responding-to-a-phone-call)
I am getting the following log:
Express server listening on port 3000
undefined
TypeError: Cannot read property 'From' of undefined
at router.post
Do you know why I am not accessing request correctly? Most examples I found have no issue accessing request.body...
Thanks,
Upvotes: 3
Views: 961
Reputation: 73057
Twilio developer evangelist here.
Twilio sends webhook requests as URL encoded form parameters. So, to read the request body in Express you need to include the Body Parser module and set the app to use the urlencoded
parser. A bit like this:
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
});
Upvotes: 8