How to integrate FCM in node.js for push notifications? - node.js

I want to add the push notification thing using FCM in Node.js .For that I tried this
and this and also this
My nodejs code
var FCM = require('fcm-node');
var serverkey = 'SERVERKEY';
var fcm = new FCM(serverkey);
var message = {
to : req.body.userToken,
collapse_key : 'XXX',
data : {
my_key: 'my value', contents: "abcv/"
},
notification : {
title : 'Title of the notification',
body : 'Body of the notification'
}
};
fcm.send(message, function(err,response){
if(err) {
console.log(message);
console.log("Something has gone wrong !");
} else {
console.log("Successfully sent with resposne :",response);
}
});
Whenever I try to run this code and start my server,I get this error in the console always.
/var/www/html/chatApp/node_modules/fcm-node/lib/fcm.js:10
function FCM(accountKey, proxy_url=null) {
^
SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/html/chatApp/node_modules/fcm-node/index.js:1:80)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Can anybody please explain what I'm doing wrong?

I used the firebase-admin package for sending the notifications (https://firebase.google.com/docs/cloud-messaging/admin/send-messages)
var admin = require("firebase-admin");
var serviceAccount = require("./firebase-adminSDK.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const messaging = admin.messaging()
var payload = {
notification: {
title: "This is a Notification",
body: "This is the body of the notification message."
},
topic: 'topic'
};
messaging.send(payload)
.then((result) => {
console.log(result)
})
The firebase-adminSDK.json can be download following the steps in https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app
This code will send a notification to the topic 'topic', however, the firebase-admin package allows sending notifications to a specific device.

Related

Azure Chatbot fails with "SyntaxError: Unexpected identifier - cosmosClient.databases.createIfNotExists" while connecting to CosmosDB

I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

RestClient has been removed from this version of the library (TWILIO)

throw new Error(this.constructor.name + ' has been removed from this
version of the library. Please refer to
https://www.twilio.com/docs/libraries/node for more information.')
^ Error: RestClient has been removed from this version of the library. Please refer to https://www.twilio.com/docs/libraries/node
for more information.
at RestClient.ObsoleteClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:7:9)
at new RestClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:12:21)
at Object. (C:\carsapp\helpers\twilio_restful_client_connection.ts:6:34)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Andrey
Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:425:12)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (C:\carsapp\helpers\sing-in-up-helper.ts:8:1)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const Client = require('twilio').RestClient;
const client = new Client(accountSid, authToken);
client.outgoingCallerIds.create(
{
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
},
(err, callerId) => {
if (err) {
console.error(err);
} else {
console.log(callerId.sid);
}
}
);
I have got this error when I tried to create this part of the code above. I tried to add a number to Twilio whitelist ( verify phone number).How can I make it in another way? I use for this Node js
Link on this part of the code in the documentation :
https://www.twilio.com/docs/api/voice/outgoing-caller-ids
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.validationRequests
.create({
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
})
.then(data => console.log(data.validationCode));
https://www.twilio.com/docs/api/voice/outgoing-caller-ids#add-an-outgoing-caller-id
Here answer on my own question

Send mail using Nodejs with HTML body

I am trying to send email from my server using nodemailer. Unfortuantely, I have been unabe to test it due to this error:
D:\Full Stack\Node\NodeLoginJWT\functions\password.js:58
'This token is valid only within two minutes.'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Full Stack\Node\NodeLoginJWT\routes.js:9:18)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
[nodemon] app crashed - waiting for file changes before starting...
This is the code block causing the error:
const transporter = nodeMailer.createTransport(`smtps://${config.email}:${config.password}#smtp.gmail.com`);
const mailOptions = {
from: `"${conifg.name}" <${config.email}>`,
to: email,
subject: 'Reset Password',
html: `Hello ${user.name}`,
'Your account password token is ${random}'
'This token is valid only within two minutes.'
'Thanks,'
'Team. '
};
return transporter.sendMail(mailOptions);
I am using Nodemailer and here is my code:
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
router.post('/', handleSendEmail); // handle the route at yourdomain.com/sayHello
function handleSendEmail(req, res) {
// Not the movie transporter!
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '', // Your email id
pass: ‘’// Your password
}
});
var text = 'Hello from \n\n' + req.body.user_name;
var mailOptions = {
from: 'sender#gmail.com', // sender address
to: 'receiver#gmail.com', // list of receivers
subject: 'Appointment Email Example', // Subject line
text: text,
html: '<!DOCTYPE html>'+
'<html><head><title>Appointment</title>'+
'</head><body><div>'+
'<img src="http://evokebeautysalon1.herokuapp.com/main/img/logo.png" alt="" width="160">'+
'<p>Thank you for your appointment.</p>'+
'<p>Here is summery:</p>'+
'<p>Name: James Falcon</p>'+
'<p>Date: Feb 2, 2017</p>'+
'<p>Package: Hair Cut </p>'+
'<p>Arrival time: 4:30 PM</p>'+
'</div></body></html>'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
}else{
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
};
});
}
module.exports = router;
I think there is a problem in your interpolation .
const mailOptions = {
from: `"${conifg.name}" <${config.email}>`,
to: email,
subject: 'Reset Password',
html: `Hello ${user.name}, // the tick should not come here
'Your account password token is ${random}'
'This token is valid only within two minutes.'
'Thanks,'
'Team. '` // the tick should come here
};

Error in sending message from an Node.js app to Slack channel

Trying to send message to slack from Node.js app
I have used following package https://github.com/xoxco/node-slack
For Detailed reference full source code is in https://github.com/sudanvellakovilkanakavel/attendence-app
I couldn't understand
what is hook_url
How to define it
Error output
CJBTDLDD0003:backend kanaks$ node readingFile.js
/Users/kanaks/Desktop/backend/readingFile.js:2
var slack = new Slack(hook_url,options);
^
ReferenceError: hook_url is not defined
at Object.<anonymous> (/Users/kanaks/Desktop/backend/readingFile.js:2:23)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
My Code
var Slack = require('node-slack');
var slack = new Slack(hook_url,options);
//var slack = new Slack(hook_url,{proxy: http_proxy});
//Trying to send message to slack from Node.js app
//I have used following package https://github.com/xoxco/node-slack
slack.send({
text: 'Meassage from node.js app to slack!',
channel: '#attendance',
username: 'Bot'
});
var fs = require("fs");
//reading the file
fs.readFile('Attendance01-04-2016.dat','utf8',function (err,data){
if (err) {
return console.error(err);
}
//spliting each line
var lines = data.split("\n");
//storeing in array and printing the file
for (i=0;i<=lines.length;)
{
console.log(lines[i]);
i=i+1;
}
});

TypeError: Object #<Object> has no method 'Request' with elastic.js

i tried the following sample code:
var es=require("elasticsearch");
var ejs = require("ejs");
var client = new es.Client({
host: 'localhost:9200',
log: 'trace'
});
client.ping({
requestTimeout: 3000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
client.search({
index: 'message-1',
type: 'message',
body: ejs.Request().query(ejs.MatchAllQuery())
}).then(function (resp) {
var hits = resp.hits.hits;
}, function (err) {
console.trace(err.message);
});
i am getting the following error when i try to run: node metric.js
/home/karunakar/test/metricagg/metric.js:27
body: ejs.Request().query(ejs.MatchAllQuery())
^
TypeError: Object #<Object> has no method 'Request'
at Object.<anonymous> (/home/karunakar/test/metricagg/metric.js:27:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
i could not locate the problem.
-- Thanks
You want the elastic.js module and not ejs, which is a templating engine module.
You can keep the first require("elasticsearch") but the second one should be require("elastic.js") instead of require("ejs")

Resources