Philip Kirkbride Philip Kirkbride - 7 months ago 13
Javascript Question

Accessing Twilio SMS Meta-Data?

Trying to access the body of an incoming text message with Twilio.

var express = require('express');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
...
module.exports = function(app) {
...
app.post('/twilio/message', jsonParser, function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.message('test body is ' + request.Body);
// I also tried JSON.stringify(request.body) to see what was in body and it returned '{ñ'
response.type('text/xml');
response.send(twiml.toString());
});
}


The following returns 'test body is undefined'. Not sure what I'm doing wrong the request data seems to be there and I can access
request.url
.

Edit: Question updated with attempt to use body-parser library.

Answer

I'm taking Twilio out of this equations (it's not the issue here). Also remember to npm install body-parser --save.

var express = require('express');
var app = express();

var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());


// listen for POSTs on /twilio/message
app.post('/twilio/message', function(req, res){
    console.log(req.body);
    res.end("End");
});

// start express
app.listen(8888);

You can test this with Postman (make sure you set x-www-form-urlencoded as your body data (or use raw with application/json) to test.

I just did to make sure it works.

I've worked with Twilio in the past and this is exactly the code we used to parse the body.