Using Twilio in Node.js, - node.js

I am trying to make an automated SMS text app using Twilio and I am having a hard time connecting it to my localhost. I keep receiving a "cannot /get" error. Basically, I am trying to send and receive messages using a webhook. Can someone take a look and see what's going on? This code was given to me by 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!');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(2001, () => {
console.log('Express server listening on port 2001');
});

Looks like you've misplaced post but wanted get (since you're trying to access the route via a get request)
change
app.post('/sms' ...
to
app.get('/sms' ...

Related

Access sender phone number twilio Node.js webhook

To respond if a user replies to a Twilio message, Twilio makes a post request to a server you can specify. How exactly can I access the sender phone number from the post request params? I want to be able to send them a Twilio message at a later date.
Example Code
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');
});
The docs say this information is given in the "post request params" but like I indicated in the example code, req.params.From is returning undefined for me.
Twilio developer evangelist here.
The from phone number, and other parameters, are sent as form encoded parameters (application/x-www-form-urlencoded) in the body of the post request. All the request parameters are listed in the documentation.
To read them, you will need to parse the body of the request using Express's urlencoded middleware (you can set this up for your application by calling app.use(express.urlencoded());) and you will then be able to read the parameters from 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');
});

How do I parse the SMS sender's from number and body of what s/he texted to Twilio number via a webhook and node.js?

Hello StackOverflow Friends:
The following code works fine, I've tested with nGrok running locally.
Two of the requirements I have left and can't figure out are:
Capture the phone number of the sender (put in variable)
Capture the body of the text the sender sent (put in variable)
Many thanks in advance!
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();
});
app.post('/sms', (req, res) => {
// Start our TwiML response.
const twiml = new MessagingResponse();
// Add a text message.
const msg = twiml.message('some canned response');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
Twilio developer evangelist here.
You can get the inbound message from an incoming SMS webhook request with req.body.Body and the inbound phone number with req.body.From.
To save into a variable, maybe something like const inbMsg = req.body.Body and const inbPhoneNum = req.body.From.
For more information on parsing an incoming Twilio SMS Webhook with Node.js, I'd recommend this blog post by my teammate Sam Agnew.
Let me know if this helps at all!

Axios can GET but not POST to the same URL

I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

Twilio 11200 HTTP retrieval failure with Node app on Heroku

My Node.js app is set to respond to a text message received at a paid Twilio number. I tested it using ngrok and everything worked fine. Once I deployed the app to Heroku, however, I started seeing an 11200 HTTP retrieval failure error in the Twilio console.
Are there configuration settings in Heroku that I need to set up?
// Twilio Credentials
const accountSid = 'xxx';
const authToken = 'xxx';
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var express = require('express');
var app = express();
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 3000));
app.use('/', function(request, response){
response.send();
});
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your
unique id # XXXX');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(app.get('port'), function() {
// console.log('Node app is running on port', app.get('port'));
});
Twilio developer evangelist here.
I think the problem is mostly in the method you are using to send the response. Currently your final line of the /sms route is res.end(twiml.toString()); however Response#end is used "to quickly end the response without any data."
I think your use of res.writeHead() might be outdated now too.
I would change your /sms route to something like this:
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your unique id # XXXX');
res.set('Content-Type', 'text/xml');
res.status(200).send(twiml.toString());
});
Then try redeploying to Heroku and see what happens.

is this the correct way to send data received from twitter api to the browser using nodejs?

I am still learning nodejs and was listening to daniel shiffman's video on how to setup the twitter api and how to get data from it.
Now, the code was working and I was getting back data, but it was all happening in the terminal.
What I wanted to do was to show the twitter data in my browser and wasnt sure how to do that. I tried searching for it, but didnt get much help.
So, I just tried doing whatever I knew and it worked and therefore I am still not sure that the code I have written is the proper way to do this.
I'd love to know if there's a mistake somewhere or If there's some other way I should have done this.
Anyways, here's the code
var http = require('http');
var express = require('express');
var app = express();
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
console.log('The bot is starting');
var Twit = require('twit');
var config = require('./config');
console.log(config);
var T = new Twit(config);
var params ={
q:'spider',
count:5
}
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
var tweets = data.statuses;
app.get('/',function(req,res){
req=params;
var tweetz='';
for(var i=0;i<tweets.length;i++){
console.log(tweets[i].text+'================================');
tweetz = '<p>'+ tweetz+tweets[i].text+'</p>';
}
res.send(tweetz);
});
}
app.listen(port, function () {
console.log(`app listening on port ${port}!`);
});
The mistake you are doing is declaring app.get inside the callback.
app.get("/", function....) is a route which responds to GET requests which means whenever a user requests for "/", the callback which is the function(req, res) is called.
So the code should be:
app.get("/", function(req, res) {
// User requested for "/" route, now get tweets
T.get('search/tweets', params, function(err, data) {
//Tweets received, now send the tweets to the user
var tweets = data.statuses;
return res.send(tweets);
})
})
Then go to http://localhost:8080/ and it should work.

Resources