so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.
const express = require("express");
const app = express();
const port = 2222;
app.get("/", function(req, resp){
resp.end("welcome to my app");
});
app.get("/:data", function(req, resp){
var accountSid = 'accountSid'
var authToken = 'authtoken'
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
})
console.log(req.params.data);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: "+req.params.data);
}
});
app.listen(port, function(err){
if(err){
console.log("error starting "+err);
return false;
}
console.log("port is running. "+port);
})
Twilio developer evangelist here.
You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.
First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:
npm install body-parser --save
Then include it in your file and use it with your app:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:
app.post("/calls", function(req, resp) {
const accountSid = 'accountSid'
const authToken = 'authtoken'
const client = require('twilio')(accountSid, authToken);
const number = req.body.number;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: number,
from: '6043302056',
}, function(err, call) {
if(err) {
console.error(err);
} else {
console.log(call.sid);
}
})
console.log(number);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: " + number);
}
});
Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.
You can load static files from the public directory in express with this line, add it near the top, after you create the app:
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:
<!DOCTYPE html>
<html>
<head>
<title>Make a call</title>
</head>
<body>
<form action="/" method="POST">
<label for="number">What number do you want to call?</label>
<input id="number" type="tel" />
<button type="submit">Make call</button>
</form>
</body>
</html>
As you can see it is just a form with a single input, the number, and a button to submit it.
Give this all a go and let me know how you get on.
Yes,
first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:
function callNow() {
var num = document.getElementById('number').value;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: num,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
{
Your HTML Code should be:
<input id="number">
<button onclick="callNow()">Call Now</button>
You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.
Related
(Please correct my terminology if it's not correct.)
My files server.js, run.js and index.html, are in the same directory.
server.js
Sets up the server.
const express = require('express');
const path = require('path');
const run = require('./run.js');
var app = express();
app.get('/index.html', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/', function(req, res){
res.redirect('index.html');
});
app.post('/run', async function(req, res){
var data = await run.run();
res.json(data);
});
app.listen(5000, function () {
console.log('Dev app listening on port 5000');
});
run.js
Will contain functions that consumes time. Here just one function as example:
async function run(){
//do time consuming stuff
var data = {
"status" : "ok",
"a1" : 1,
"a2" : 2
};
return data;
}
module.exports = {
run:run
}
index.html
Simple form.
<!DOCTYPE html>
<html>
<body>
<form id="search-form" action="/run" method="post">
Input:<br>
<input type="text" name="input1" id="input1" value = ""> <br>
<input type="submit" value = "Run">
</form>
<script></script>
<div id="data"></div>
</body>
</html>
When I run the server, go to localhost:5000 in the browser, and click the run button, I get redirected to a page just showing the content of data.
What I would like to happen when I click the the run button is;
The server process /run post request
A response is sent with res.json or res.send to the client
A javascript script on the client side should catch the response, process it, and make some change to the html code (in my case, create some table).
How can I achieve this?
So your problem is that you're using a form. Forms will redirect you to the specified web page with all of the form's data.
You need an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/run", true);
xhr.send();
If you ever need the data of your form to be submitted as well, I have some documentation on how to do that.
Hope this helps!
I'm new to Node.js and JavaScript. I have a specific problem but mostly need advice on the best solution.
I'm running a Node server. I want the client to be able to submit a string to the server, then the server to display a new HTML page that shows the string data.
I'm using Express and Socket.io.
In the following files, the client sees index.html, then after submitting the form it sees return.html. I print the input string to the console, and the output is as expected (whatever the user enters). But the return.html is never updated with the input string.
I also tried sending the return.html page and the change_result call in an async series, but the sendFile function never ends and the second function in the series is never called. In previous attempts it worked intermittently with a setTimeout around the emit('change_result') function.
Why doesn't the call to change_result do anything? I used the same technique to update the headings of the original index.html in previous versions. Should I be routing to localhost.../return.html and sending the post data there, or something like that?
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser') //for POST request
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
server.listen(8080, function() {
console.log("Server running on port 8080.");
});
var dir = __dirname;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
var query1=req.body.input1
console.log("Server: In post request.")
console.log(query1);
res.sendFile(dir + '/return.html');
io.emit('change_result', {
result: query1
});
});
index.html
<!DOCTYPE html>
<html>
<body id="body">
<form method="post" action="http://localhost:8080">
String: <input type="text" name="input1" id="input1" />
<input type="submit" id="button1" value="Submit" />
</form>
</body>
</html>
return.html
<!DOCTYPE html>
<html>
<body id="body">
<p id="heading1">Result: </p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result"\"";
});
});
</script>
</body>
</html>
I'm not knee-deep inside socket.io, but IMO the problem is, that the server has no way to know if any listeners are ready.
I think you should emit a 'ready' event, once the return.html is loaded, then listen to 'change_result'. Also separate the socket communication from the POST response on the server. Like so.
server.js
var query;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
query = req.body.input1;
console.log("Server: In post request.");
console.log(query);
res.sendFile(dir + '/return.html');
});
io.on('connection', function(socket) {
socket.on('ready', function() {
socket.emit('change_result', {result: query});
});
});
return.html
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.emit('ready', function(data) {});
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result + "\"";
});
});
</script>
So I am trying to link this interface to a server so that the message I input in the front end is Posted in a separate webpage hosted on the server. eg "Hello [name]"
This is the interface:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="Insert message here">Message: </label>
<input type="text" id="message" name="message"></input>
</div>
and this is the server I am trying to post the message to:
var express = require('express');
var app = express();
app.use(express.static('public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/userlogin", function(request, response) {
response.send( "Hello " + request.body.message );
});
app.listen(process.env.PORT || 8080, process.env.IP);
I am just not sure how to make the interface and server talk to each other. I would also like to store all the messages in a db too, but that is for later after I figure this out.
Thanks!
Right now your form submits to /userlogin. You should define that route in your server like this:
app.post('/userlogin', function(req, res){
res.send('Hello' + req.body.message);
}
req.body is basically the post data submitted by your form, in this case only the input named 'message.'
any time you wish to submit a form to a node server, ensure the action corresponds to a route or method with an identical name.
From your html ...
app.post('/userlogin', function(request, response) {
response.send( "Welcome, your message is: " + request.body.message );
});
I'm totally new to node.js and I want to implement push notification system on a MySql database. I have a notification table in my database. In this table I have store recipient_id that specify the recipient of the notification. Now I want when a new notification with recipient_id is equal to current logged in user's id notify that user. Something like Stackoverflow If you are in the for example java tagged questions, every time a new question with java tag create, a notification appear on top of the page : 1 question with new activity.
Sorry for my poor English. Please help me to implement this system, because I'm new to it.
I have made a simple app like your requirement.
You can get help from following lines of code.You need to understand the basics of code. after that you will easily achieve your target. most of things from your requirement covered in this demo app.
Its not a exact but you will meet your target through this.
In this example a status post by any user will emit to all other users also at same time. we can manipulate it to achieve "1 new status".
make a table in database where your entries to be saved
CREATE TABLE status
(
`status_id` INT NOT NULL AUTO_INCREMENT,
`s_text` TEXT,
`t_status` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `status_id` )
);
//server.js
var app = require("express")();
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: '',
database: 'fbstatus',
debug: false
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
socket.on('status added', function(status) {
add_status(status, function(res) {
if (res) {
io.emit('new status', status);
} else {
io.emit('error');
}
});
});
});
var add_status = function(status, callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('" + status + "')", function(err, rows) {
connection.release();
if (!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
//index.html
<html>
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
$("#add_status").click(function(){
socket.emit('status added',$("#comment").val());
});
socket.on('new status',function(msg){
var count = $('#count_status').text();
var valCount = parseInt(count);
if(valCount>=1) {
valCount = valCount+1;
} else {
valCount = 1;
}
var showMsg = '<div id="count_status"> '+valCount+' </div> new status';
$("#show_comments").html(showMsg);
});
});
</script>
</head>
<body>
<div id="comment_box" style = "padding:5%;">
<textarea id="comment" rows="5" cols="70"></textarea><br /><br />
<input type="button" id="add_status" value="Add">
</div>
<div id= "show_comments" class = "jumbotron"></div>
</body>
</html>
Run the app with following command
node Server.js
Now run http://localhost:3000/ in browser and to see the result open a new window in which you post a status and see your new status notification in both the window.
Thanks
Edited: This a great startup tutorial. a few thing needs modification.
connection.release() code ends up unreadable and not working. you should comets or remove it.
2.The actual output in my case:
You can do it 2 ways:
Query the server every n seconds for any new messages. Pass a timestamp of the last time you checked as a parameter and if any notification since the last check, return as json and display them in the client. This is called a pull strategy.
Or you can use websockets which maintains a permanent connection between your client and server, and then you can send notifications to the client from your server code in real-time. See socket.io tutorials. This is called a push strategy.
I'm trying to display a message after or before a redirect. I looked around the site but I found only jquery and php but I can only use the normal java language. In particular I'm trying to use a div that could be good for me. The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID). Can you help me? Here is my code:
var express = require('express');
var router = express.Router();
var middleware = require('../middleware');
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var User = mongoose.model('User');
var config = require("../../config");
var session;
router.all('/', middleware.supportedMethods('GET, POST'));
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', function (req, res) {
var post = req.body;
var query = User.where({userName : post.username});
query.findOne(function(err, user){
if (err) { return err}
if (user) {
user.isValidPassword(post.password, function(n, isMatch){
if(isMatch) {
req.session.user_id = user._id;
res.redirect('/library?' + user._id);
} else{
res.redirect('/login');
}
});
}else{
res.redirect('/login');
}
});
});
module.exports = router;
I would put my message on the res.redirect('/login') (both of them) with two different message. I don't know if I have to create a new page, identical, with a div message or I could find a better solution...
I'm trying to display a message after or before a redirect...The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID).
Exactly. So you can't do that. Instead, you need to return a redirect to a page with your message on it, and then have that page continue on (after a period of time, or after a user action) to the ultimate destination (/login or whatever).
A minimal intermediary page might look like this:
<!doctype html>
<html>
<head>
<title>Some Relevant Title</title>
<meta charset="utf-8"></meta><!-- Or whatever is appropriate -->
<meta http-equiv="refresh" content="15; url=/login">
</head>
<body>
Message goes here. With the refresh above, the page will refresh after 15 seconds.
</body>
</html>