Send/receive data from Javascript to Node.js using Express - javascript

I am currently working with the Express platform, the Twilio Node.js SMS API and obviously javascript to send text messages to my users. Problem is, I don't know what I should do in order to send data through my GET variables on the front-end and capture those values with node.js on the back-end.
For testing purposes, I created a simple button that sends a text message to a fixed number when clicked.
Here is the javascript side:
function sms() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:5001", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
Here is the node.js side:
var accountSid = 'ACCOUNT_SID';
var authToken = 'ACCOUNT_TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
var express = require("express");
var app = express();
app.get('/',function(request,response){
var to = "TO";
var from = "FROM";
client.messages.create({
to: to,
from: from,
body: 'Another message from Twilio!',
}, function (err, message) {
console.log("message sent");
});
});
app.listen(5001);
I have came across two ways to send a responseText from Node.js, but can't manage to make them work
first one using response.send("Hello World"); or the second one response.write("Hello again"); response.end();
So just to sum it up, I want to send variables (to, from, message, etc.) through my http request, capture them in node.js and send a responseText! As a heads up, I'm very comfortable with AJAX requests between JS and PHP, but Node.js is new to me.
Thanks in advance

I think the new Guides will help you out here with How to receive and reply to SMS in Node.js:
https://www.twilio.com/docs/guides/sms/how-to-receive-and-reply-in-node-js
The CodeRail along the right hand side will walk you through it step-by-step but you should pay attention particularly to the section titled "Generate a dynamic TwiML Message".
var http = require('http'),
express = require('express'),
twilio = require('twilio'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function(req, res) {
var twilio = require('twilio');
var twiml = new twilio.TwimlResponse();
if (req.body.Body == 'hello') {
twiml.message('Hi!');
} else if(req.body.Body == 'bye') {
twiml.message('Goodbye');
} else {
twiml.message('No Body param match, Twilio sends this in the request to your server.');
}
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(1337, function () {
console.log("Express server listening on port 1337");
});

Related

Extracting of HTTP Post in Node Express doesn't work

I just want to extract an http-Post but I didn't get it working. Can somebody help me please? The request is made by my HTML Frontend using XMLHttpRequest() and the backend is node.js. When I send the request I only get an empty Object {}
Node Backend
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
app.use(express.json());
app.post('/save_options', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
Frontend
let DATA_FRONTEND_OPTIONS = {
"test":"1"
}
function save_options_to_database() {
var do_it_async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status;
var data = request.responseText;
}
request.open("POST", "/save_options", do_it_async);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send(JSON.stringify(DATA_FRONTEND_OPTIONS));
}
Simply add
app.use(express.urlencoded());
to your express configuration.
Here is great explanation:
https://stackoverflow.com/a/51844327/8522881
You have to add express.json() and express.urlencoded() for POST request.
Example:
app.use(express.json());
app.use(express.urlencoded());
Because in POST request the data which is sending is in form of some type of data object and you have to tell the server to accept or store that type of data (object), which is enclosed in the body of your POST request.
Above the same solution applied for PUT requests also.

ExpressJS and http(ajax?) call doesnt work?

im trying to do a simple ajax call but somehow it doesnt work.I cant figure it out, would be nice if someone could help me.
Server script :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.get('/test1', function (req, res) {
res.send('GET request to the homepage');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Button that runs a client based JS
<button onclick="callServerSideScript('key','port','address','username','password','gem','proxy','crypt')" type="button" id="build">Get build</button>
Client based JS :
function callServerSideScript(key,port,address,username,password,gem,proxy,crypt){
keyVal = document.getElementById(key).value;
portVal = document.getElementById(port).value;
addressVal = document.getElementById(address).value;
userVal = document.getElementById(username).value;
pwVal = document.getElementById(password).value;
gemVal = document.getElementById(gem).checked;
proxyVal = document.getElementById(proxy).checked;
crytpVal = document.getElementById(crypt).checked;
httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/test1');
httpRequest.send('some data');
}
Normally it should do a /test1 request to the server and the server should react to it? I am missing something?
eighter do httpRequest.open('GET', '/test1'); (client) or app.post('/test1', handler); (server). but if your sending a POST request and the server expects a GET request it just gets 404'd

How to send post request to server.js in cloud9

Hi I'm learning the mean stack on cloud9.
I've come to the point where I'm trying to send variables to my node.js server but I'm not sure if my server is picking it up. Are there any obvious errors with my post request code?
app.js(frontend angular)
console.log('begin');
var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
console.log('onreadystatechange');
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
else {
console.log('readyState=' + http.readyState + ', status: ' + http.status);
}
}
console.log('sending...')
http.send(params);
console.log('end');
this is the console response that I am getting:
begin
sending...
end
POST https://new-backup.splacorn.c9.io/myApp/server/server.js/ net::ERR_INSECURE_RESPONSE$scope.addNewUser
onreadystatechange
readyState=4, status: 0
I believe that the error that I am getting is attributed to this line:
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
once http.send(params); calls it.
Here is the server.js file (backend)
var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser')
app.use(express.bodyParser());
app.post('/', function(req, res){
console.log('POST /');
res.writeHead(200);
res.end('this is from the server');
});
var port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port);
Does anyone know why I'm getting the error? Part of me thinks that I'm getting the cloud 9 server url wrong but I'm not sure... If anyone can help me figure this out that would be amazing!
I'd like to use socket.io instead.
Here's a small example of how you can do it:-
Client side code:
var io = io("http://localhost:1337");
io.emit('give me some data',{test:'testing socket.io'});
io.on('got the data',function(data){
console.log(data.test);
});
Server side code:
var app = require('express').createServer();
var io = require('socket.io')(app);
io.on('connection',function(socket){
socket.on('give me some data',function(data){
socket.emit('got the data',data);
}
app.listen(1337);
You can get socket.io here
They have both client side as well as server side code. Hope you got my point. I was at phone so couldn't type much. And also, socket.io provides real time connection between the client and the server :)

AJAX POST JSON from javascript to nodejs server

I'm trying to send a JSON object from javaScript to node.js server. I'm using a standard XMLHttpRequest to send it from javascript and a standard node.js code.
Two codes seem to be communicating normally however the node.js always gives me an empty JSON object. I'm not really sure what am I doing wrong.
This is my javascript code:
<html>
<head>
<script>
function xhrPost() {
var data = {"name":"John", "time":"2pm"};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://[serverIP]:8080/addUser");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
}
</script>
</head>
<body onload="xhrPost()">
</body>
</html>
and this is my node.js code:
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/addUser", function(request, response) {
console.log(request.body); // this line allways produce {}
response.send("Message received.");
response.end();
});
app.listen(8080);
You have to use myParser.json() as a middleware. See more about it in https://github.com/expressjs/body-parser#bodyparserjsonoptions
After following line:
var myParser = require("body-parser");
You should add on more line as:
var myParser = require("body-parser");
app.use(myParser.json());// parse application/json
This was the most helpful stackoverflow page to solve my problem as well.
I was trying to get form fields, formulate them into a JSON on the client, then send to the server to use the fields for a MySQL call to a separate database.
Object {name: "", reps: "1", weight: "1", date: "", lbs: "0"}
I was able to get the object logging correctly on the client, yet every time I tried to send the data to the server,
console.log(req.body);
Would always return on the server as either
{}
undefined
Server side my setup with functioning data passing is
var express = require('express');
var mysql = require('./dbcon.js');
var app = express();
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var request = require('request');
var myParser = require("body-parser");
var async = require('async');
app.set('view engine', 'handlebars');
app.set('port', Number(process.env.PORT || 3000));
app.use(myParser.json());
app.use(express.static('public'));
app.engine('handlebars', handlebars.engine);
On my client side js file, I have a function upon form submit that does:
var data = {
"name":document.getElementById("fname").value,
"reps":document.getElementById("freps").value,
"weight":document.getElementById("fweight").value,
"date":document.getElementById("fdate").value,
"lbs":bool
};
...
req.open("POST", "/insert", true);
req.setRequestHeader("content-type", "application/json;charset=UTF-8");
...
req.send(JSON.stringify(data));

Receive text message with Twilio node module and respond with a text message

var http = require('http');
var twilio = require('twilio')(ACCOUNT_SID, AUTH_TOKEN);
var qs = require('querystring');
http.createServer(function (req, res) {
var body = '';
req.setEncoding('utf8');
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var data = qs.parse(body);
var jsonString = JSON.stringify(data);
var jsonDataObject = JSON.parse(jsonString);
// log the received message
console.log(jsonDataObject.Body);
twilio.messages.create({
to:'MY_PHONE_NUMBER',
from:'TWILIO_NUMBER',
body:'Hello World'
}, function(error, message) {
if (error) {
console.log('There was an error.')
console.log(error.message);
}
});
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end();
});
}).listen(1337, '127.0.0.1');
console.log('TwiML servin\' server running at http://127.0.0.1:1337/');
I'm trying to use the Twilio node module to receive a text message and in turn respond to that text message once received. There seems to be no problem receiving the message as I'm able to log the body. But, I get a 401 Authenticate error when I try and respond to that message. I'm using ngrok to expose my localhost so I can hook it into Twilio's API. Please see below:
Where am I going wrong here?
Twilio developer evangelist here.
You actually don't need to use the REST API in order to reply to an incoming message to a Twilio number. You can, in fact, respond to the incoming HTTP request with TwiML that describes the message in response.
To do this, you need to use the <Message> verb. In your application, this would look like:
First, just require the twilio module without the account credentials:
var twilio = require("twilio");
Then, respond to the incoming request with TwiML, like so:
req.on('end', function() {
var data = qs.parse(body);
var jsonString = JSON.stringify(data);
var jsonDataObject = JSON.parse(jsonString);
// log the received message
console.log(jsonDataObject.Body);
var twiml = new twilio.TwimlResponse();
twiml.message("Hello world");
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
Let me know if this helps at all.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var server = app.listen(80, function () {
var host = server.address().address
var port = server.address().port
console.log(" web app listening at http://%s:%s", host, port)
})
app.post('/txt', urlencodedParser,(req, res) => {
const twiml = new MessagingResponse();
twiml.message('Finally Twilio works!');
res.status(200);
res.send(twiml.toString());
});
Under your phone number in the console.
You can click webhooks and change it to the http://"putyourserverhere"/txt
This will automatically text back the inbound user.
Enjoy. Make sure you have the newest version of twilio installed.

Categories

Resources