Make voice call using node js - node.js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

Related

keep getting 401 using request package

My code is not working, I can't figure out why and it keeps giving me a 401 meaning the API key is missing so I don't know how this is happening and I would like to figure out what my problem is on this piece of code?
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var data = {
members: [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
url: "https://us20.api.mailchimp.com/3.0/lists/listId"
method: "POST",
headers: {
"Authorization": "mkouk24 Api Key"
},
body: jsonData
};
request(options, function(error,response,body){
if (error) {
console.log(error);
} else {
console.log(response.statusCode);
}
});
});
app.listen(3000, function() {
console.log("Server is running on port 3000!");
});
First of all, according to the documentation, I think you need to use app.use(bodyParser.json()) in order to pass parameters in post request.
Second, you should generate an API token from MailChimp and add it here Authorization": "mkouk24 Api Key"
More on that on this link: https://mailchimp.com/help/about-api-keys/

POST event on outlook calendar using node.js : error InvalidAuthenticationToken

I am using this code to authenticate on Outlook Calendar (Oauth2) and then post an event to my calendar. I'm getting an error that after my first authentication the token is expired so O can't post on the calendar. If someone can help to find the error in my code :)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var moment = require('moment');
var querystring = require('querystring');
var outlook = require('node-outlook');
var microsoftGraph = require("#microsoft/microsoft-graph-client");
var currentToken;
var authHelper = require('./authHelper');
// 3- Configure express
// Set up rendering of static files
app.use(express.static('static'));
// Need JSON body parser for most API responses
app.use(bodyParser.json());
// Set up cookies and sessions to save tokens
app.use(cookieParser());
app.use(session(
{ secret: '************',
resave: false,
saveUninitialized: false
}));
// 4- Home page
app.get('/', function(req, res) {
res.write('<a id="signin-button" class="ms-Button ms-Button--primary"
href="'+authHelper.getAuthUrl()+ '"><span class="ms-Button-label">Click here
to sign in</span></a>');
res.end();
});
app.get('/authorize', function(req, res) {
var authCode = req.query.code;
if (authCode) {
console.log('');
console.log('Retrieved auth code in /authorize: ' + authCode);
authHelper.getTokenFromCode(authCode, tokenReceived, req, res);
}
else {
// 5- redirect to home
console.log('/authorize called without a code parameter, redirecting to
login');
res.redirect('/');
}
});
// 6- if it can't take the token
function tokenReceived(req, res, error, token) {
if (error) {
console.log('ERROR getting token:' + error);
res.send('ERROR getting token: ' + error);
}
else {
// 7- save tokens in session
req.session.access_token = token.token.access_token;
req.session.refresh_token = token.token.refresh_token;
req.session.email = authHelper.getEmailFromIdToken(token.token.id_token);
res.redirect('/logincomplete');
}
}
// 8- login complete
app.get('/logincomplete', function(req, res) {
var access_token = req.session.access_token;
var refresh_token = req.session.access_token;
var email = req.session.email;
currentToken = access_token;
var http = require("https");
var options = {
"method": "POST",
"hostname": "graph.microsoft.com",
"port": null,
"path": "/v1.0/me/events",
"headers": {
"authorization": "Bearer 'access_token'",
"content-type": "application/json",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write("{\n \"subject\": \"My M\",\n \"start\": {\n \"dateTime\":
\"2017-11-30T15:34:40.942Z\",\n \"timeZone\": \"UTC\"\n },\n \"end\":
{\n \"dateTime\": \"2017-12-07T15:34:40.942Z\",\n \"timeZone\":
\"UTC\"\n }\n}");
req.end();
});
// Start the server
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

How to start a conversation from nodejs client to microsoft bot

I'm trying to build an app that would send messages to a chat on Microsoft bot framework based on Directline lib, and reply with answer. The app is a web application where should send a POST request that should forward the message to the bot client, and reply with response of the bot from Microsoft bot framework.
An example of HTTP POST request:
http://host:port/api/message
BODY: {message:"Hi"}
It should send the "Hi" as a text to the relevant chat bot in the Microsoft Bot framework and reply with what ever the framework replys with.
I have put the secret and done all i think i should have done in order it to be working but, i'm having problem generating a conversation that should talk with the chat bot.
This is how i did it:
"use strict";
require('dotenv').config();
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require("body-parser");
var http = require('http');
var postLib = require("./lib");
var messageFilePath="message.out";
var cors = require('cors');
var uuid = require('uuid');
//new botclient
var client = require('directline-api');
// config items
var pollInterval = 1000;
var directLineSecret = 'secret';
var directLineClientName = 'DirectLineClient';
var directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';
///bot client end
var sendmail = require('sendmail')({silent: true})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.options('*', cors()); // include before other routes
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.post('/interact/message', cors(corsOptions), function(req, res) {
var uuid1 = uuid.v1();
var bodyMessage = JSON.stringify(req.body);
var log = uuid1 + ', ' + new Date().getTime() + ", " + bodyMessage;
if (req.query.botId == 1) {
emailMessage(log);
res.send(postLib.reply.reply);
}
if (req.query.botId == 2) {
botMessage(bodyMessage.message);
res.send(postLib.reply.reply);
}
});
function emailMessage(log){
sendmail({
from: postLib.mail.from,
to: postLib.mail.to,
subject: postLib.mail.subject,
html: 'this is the log: [' + log + ']',
}, function(err, reply) {
console.log(err && err.stack);
console.dir(reply);
});
fs.appendFile(messageFilePath, "\n" + log, function(error){
if (error) throw error;
});
}
function botMessage(message){
var token = client.getToken(directLineSecret);
// create a conversation
var conversationId = client.createConversation(token);
// post a message in a conversation
client.postMessage(token, conversationId, {
text: message
});
return client.getMessage(token, conversationId, 0);
}
var server = app.listen(8082, function () {
var host = server.address().address
var port = server.address().port
console.log("interact post server listening at http://%s:%s", host, port)
})
It's unclear the issue that you are having but I recommend you to check the Node.js Direct Line sample.

request body parameters are undefined in nodejs busboy

I am using formdata to have multipart data and for that i am using busboy-body-parser. But somehow the body is not accessible and the value is undefined.
app.js
var express = require('express');
var mongoose = require('mongoose');
var Uploader = require('s3-image-uploader');
var config = require('./config.js');
var busboyBodyParser = require('busboy-body-parser');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var multer = require('multer');
// var uuid = require("uuid");
var app = express();
var morgan = require('morgan');
var path = require('path');
var port = process.env.PORT || 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var login = require('./controller/login.js');
var itemInfo = require('./controller/item_info.js');
var review = require('./controller/reviews.js');
var popularitems = require('./controller/popularitems.js');
var foodtruck = require('./model/datafoodtruck');
var truckData = require('./model/foodtruck.js');
var webToken = require('./controller/webtoken.js');
var userprofile = require('./controller/userprofile.js');
var notificationdata = require('./model/dataNotifications.js');
var notification = require('./controller/notifications.js');
var foodtruckItemList = require('./controller/item_list_foodtruck.js');
var orderList = require('./controller/orders_foodtruck.js');
var ordermanagement = require('./controller/ordermanagement.js');
var db = mongoose.connect(config.local_mongo_url);
mongoose.connection.once('connected', function() {
console.log("Connected to database")
// foodtruck.save();
// notificationdata.save();
});
app.use(bodyParser.urlencoded({
extended: true
}));
// app.use(multipartyMiddleware);
app.post('/testupload', function(req, res) {
// var file = req.files.file;
// var stream = fs.creatReadStream(req.files.file.path);
// return s3fsImpl.writeFile(file.originalFilename, stream).then(function() {
// console.log(file);
// return;
// fs.unlink(file.path, function(err) {
// if (err) console.error(err);
// res.json({
// status: '200',
// message: 'uploaded'
// });
// });
// })
res.connection.setTimeout(0);
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/food-3-mdpi.png',
name: 'food-3-mdpi.png'
},
function(data) { // success
// console.log('upload success:', data);
res.json({
status: '200',
message: 'image uploaded successfully'
});
},
function(errMsg, errObject) { //error
// console.error('unable to upload: ' + errMsg + ':', errObject);
res.json({
status: '404',
message: 'image is not uploaded successfully'
});
});
});
// app.use('/public/images', express.static(__dirname + '/public/images'));
app.use(morgan('dev'));
// app.use(bodyParser.urlencoded({extended: true}));
app.get('/foodtrucklist', foodtrucklist);
app.post('/itemInfo', itemInfo.itemInfo);
app.post('/likeitem', itemInfo.likeItem);
app.get('/popularitems', popularitems);
app.post('/notification', notification);
app.post('/submitreview', review.addreview);
app.post('/getreview', review.getReview);
app.post('/addOrder', ordermanagement.addOrder);
app.post('/orderHistory', ordermanagement.orderHistory);
app.post('/cancelOrder', ordermanagement.cancelOrder);
app.post('/getOrderStatus', ordermanagement.getOrderStatus);
app.post('/rateOrder', ordermanagement.rateOrder);
app.post('/updateUser', userprofile.updateUser);
app.post('/getUserInfo', userprofile.getUserInfo);
app.post('/createToken', webToken.createToken);
app.post('/checkToken', webToken.checkToken);
app.post('/itemList', foodtruckItemList.getItemList);
app.post('/updateItemStatus', foodtruckItemList.updateItemStatus);
app.post('/addItem', foodtruckItemList.addItem);
app.post('/deletItem', foodtruckItemList.deletItem);
app.post('/orderlist', orderList.getOrderList);
app.post('/statusOrderlist', orderList.getStatusOrderList);
app.post('/updateorder', orderList.updateOrder);
app.use(bodyParser.urlencoded({extended: false}));
app.use(busboyBodyParser({ limit: '50mb' }));
app.post('/login', function(req,res) {
console.log("body" + req.body.email_id + "file" + req.files);
});
app.listen(port, function() {
console.log('express listining on port' + port);
});
so, how can I access body parameters even I tried to use multer but the problem was same.
Busboy has parameters inside busboy.on('field') event
We explicitly have to attach it to req.body before Busboy.on('finish') event like so :
busboy.on('field', (fieldName, value) => {
req.body[fieldName] = value
})
This will attach parameters to req.body as it should be !

Start a proxy server with nodejs so that it serves requests preprended with "/wps_proxy/wps_proxy?url="

I want to start a proxy server with node.js so that it serves requests preprended with "/wps_proxy/wps_proxy?url=". I want it so I can use the wps-js library of north52 (check the installation tips) . I have already a server where I run my application.
What I did try until now is :
the server.js file
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require("path");
var app = express();
app.use(express.static(__dirname + '/' + 'public'));
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//****** this is my try ******************************
app.get('/wps_proxy/wps_proxy',function (req,res){
res.sendfile(__dirname + '/' + 'public/wps_proxy/wps-js/target/wps-js-0.1.2-SNAPSHOT/example.html');
if(req.query !== undefined){//because it enters sometimes without url
var http = require('http');
//Options to be used by request
var options = {
host:"geostatistics.demo.52north.org",//fixed given data
port:"80",
path:"/wps/WebProcessingService"
};
var callback = function(response){
var dat = "";
response.on("data",function(data){
dat+=data;
});
response.on("end", function(){
res.end(dat)
})
};
//Make the request
var req = http.request(options,callback);
req.end()
}
})
var ipaddress = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.set('port', port);
app.listen(app.get('port'),ipaddress, function() {
console.log( 'Server started on port ' + app.get('port'))
})
//***************************************
but its not working.. I think that the data are not sent back correctly..
This is a live example of what I want to do.. http://geoprocessing.demo.52north.org/wps-js-0.1.1/
and this is a live example of my application (check the console for errors) http://gws-hydris.rhcloud.com/wps_proxy/wps_proxy
I did find my answer from this post How to create a simple http proxy in node.js? so the way i solve it was:
app.get('/wps_proxy/wps_proxy',function (req,res){
var queryData = url.parse(req.url, true).query;
if (queryData.url) {
request({
url: queryData.url
}).on('error', function(e) {
res.end(e);
}).pipe(res);
}
else {
res.end("no url found");
}
})

Resources