Twilio.Device.connect() not sending body to Express - node.js

I'm developing in JS, React on the frontend, and Node, Express on the backend.
I have a call button that I press that I want to start an outgoing call via Twilio. I've got a Node server with a couple endpoints, one to generate a token and the other is the voice url.
On the frontend, I'm making a Twilio.Device and have it logging when it's ready. I click on the button, that hit's Twilio's example SDK function that calls Twilio.Device.connect() and I am passing {number: n} into it.
On the backend, the request is made and the voice url is hit, but without a body. When I try logging req.body, it's just an empty object.
When I try hitting the Node server directly from Postman, with the same body ({number: '+11231231122'}) I see everything in the log.
Something is happening between the front and backends, but I cannot figure out what it is.

Twilio developer evangelist here.
Twilio will be sending the body, but as you are using Express it is likely that you aren't parsing that body properly.
Twilio sends requests as url encoded parameters, so you need to use body-parser to parse the body into req.body within a request. Try setting your app like so:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

Related

In new express where body-parser is implicit, how to get raw request body in middleware?

I would like to get the raw request body in one of my middlewares in my Express app. There are a few posts on Stackoverflow that show how to do this (e.g. Node.js - get raw request body using Express or Writing express middleware to get raw request body before body-parser), but:
They use body-parser, which I believe is built-in with the new Express version, so am not sure how to use it in this case
They extract the raw request in app.use(), which means that all routes would extract the raw request, whereas I only want to extract it in one route (more specifically, in an independent middleware that's buried deep in my code rather than in app.js, to which I want to be able to just pass the req element and extract its raw body there).
Any advice on the best way to do this?
Assuming you have not already parsed the body before reaching this route (using body-parser or something similar), following will work in your routes file:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.get('/path', bodyParser.raw(options), (req,res){
//your code
});
bodyParser.raw(options) will return a function that accepts 3 arguments (req,res,next) and the raw body will become available in req.body

how to handle post data in client on express

I am using express.js to built the website. i use .ejs as my front end and nodejs for backend i want ejs to interact with the nodejs server. I use get request and i split the url and taking the data but its no where good so i want to interact ejs file to nodejs for eg when we are using php we will try to code as $_POST['somename'] and even we do dynamic programming in php by taking the data and embedding html and writing it. i want to know to handle post request in ejs file and store the post request data and handle it throughout the file
As far as I understood you want to handle your form data, and in order to do so you have to use body-parser.
npm install body-parser
then in your app.js/server.js just add these lines
let bodyParser = require("body-parser")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
after that you will be able to get $_POST['name_here']
app.post("/whatever", (request, respone){
console.log(request.body.name_here) //same as $_POST['name_here']
})

How do I read an SMS message sent to my Twilio phone number?

I couldn't find this in Twilio's API docs.
I use NodeJS. When a user texts my Twilio number, I want to use NodeJS to retrieve the message.
Where can I find this in Twilio's API reference?
Twilio developer evangelist here.
When a user texts your Twilio number there are two ways to get that message.
The first is the most efficient and uses webhooks. When you purchase your Twilio number you can configure a URL for Twilio to make a request to every time it receives an SMS for that number. The request will include a bunch of parameters, including the number the message is from and the body of the message. You can receive the request with a Node.js app, here's a quick example using express:
var app = require("express")();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: false});
app.post("/messages", function(req, res) {
console.log(req.body.Body); // the message body
console.log(req.body.From); // the number that sent the message
res.send("<Response/>"); // send an empty response (you can also send messages back)
});
app.listen(3000); // listens on port 3000
When developing an app that uses webhooks like this, I recommend tunneling to your local machine using ngrok.
The other way to get your messages is by using Twilio's REST API. You can list all the messages to your numbers using the messages resource. In Node.js, this would look like:
var client = require('twilio')(accountSid, authToken);
client.messages.list(function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body);
});
});
Let me know if this helps at all.

Twilio Message Params Empty

I am testing out Twilio and am attempting to receive an SMS message. When I send a text, my app route is getting triggered as expected, however the "params" are empty. I've tried both post and get. Using Express (and Coffeescript), here is what I've got (not much to it):
app.post '/receive', (req, res) ->
console.log req.params
In this case, it logs out an empty object. Any ideas?
req.params refers to URL parameters in Express 4. Twilio sends HTTP POST parameters (by default) with a webhook request. Are you using a body parser middleware?
https://github.com/expressjs/body-parser
With this module, if you use the form-encoded middleware, the parameters sent from a Twilio POST request will be in req.body. If Twilio sends you a GET, the parameters should be in req.query without using any additional middleware.
Thanks,
-Kevin

Twilio $_REQUEST['From'] equivalent for node.js

I'm trying to use 'twilio' to grab the caller ID from an incoming phone call. I managed to do this easily in my call.php file using the following:
$callerId=($_REQUEST['From']);
I have now redirected my twilio phone number to access a different URL so that I can use it with node.js (ie call.php is now call.js). However, I cannot seem to request the ['From'] field in a similar manner as with the .php file. Is this possible? What is the easiest way to grab a caller Id and store it in a variable using node.js?
Any thoughts appreciated.
For the sake of completeness, here's a full example of getting Twilio request parameters using Express. Before running, make sure to install dependencies with npm install twilio express. You might also benefit from reading this blog post introducing the Twilio node.js module.
This code is an example of responding to an inbound phone call:
// Module dependencies
var twilio = require('twilio'),
express = require('express');
// Create an Express webapp, and use a middleware
// that parses incoming POST parameters
var app = express();
app.use(express.urlencoded());
// Create a route that responds to a phone call by saying
// the caller's number
app.post('/call', function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.say('Hello, you called from ' + request.param('From'));
response.type('text/xml');
response.send(twiml.toString());
});
// Start the app on port 3000
app.listen(3000);

Resources