How to solve [{"error":"InvalidRegistration"}] - node.js

What im trying to do is to make push notifications using Expo Server. I have followed the expo documentation for the front end: https://docs.expo.dev/push-notifications/push-notifications-setup/.
In the backend is used this code:
exports.pushNotification = asyncHandler(async (req, res, next) => {
const { someExpoPushTokens } = req.body;
let allToken = [];
for (let i in someExpoPushTokens ) {
allToken.push(someExpoPushTokens [i].token);
}
let firebaseServerKey =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..."; // server key
var notificationData = JSON.stringify({
registration_ids: allToken, // the expo token
priority: "high",
content_available: true,
notification: {
title: "title",
body: "body",
sound: "default",
},
});
var config = {
method: "post",
url: "https://fcm.googleapis.com/fcm/send",
headers: {
Authorization: `key=${firebaseServerKey}`,
"Content-Type": "application/json",
},
data: notificationData,
};
axios(config)
.then(function (response) {
console.log("res.data.resulet", JSON.stringify(response.data.results));
console.log("config: ", config);
})
.catch(function (error) {
console.log(error);
strapi.plugins.sentry.services.sentry.sendError(err.message);
});
});
So I get the expo token push notification from the frontend.
And the error I get in my logs is: res.data.result [{"error":"InvalidRegistration"}]
Is there any way how to make it work with expo token?
How can I solve this?

Related

One signal push notification node js API

Push notification node js API using One signal
Hello guys, I've watched a tutorial to implement push notifications on flutter app project.
the code I'll show is how to set up a push notification on node js API using one signal.
I need help to know how to view the notification using One Signal API.
here is the notification service folder
notification.services.js
const { ONE_SIGNAL_API_KEY } = require('../utils/config')
const { info } = require('../utils/logger')
const sendNotification = async (data, callback) => {
const headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: 'Basic ' + ONE_SIGNAL_API_KEY,
}
const options = {
host: 'onesignal.com',
port: 443,
path: '/api/v1/notifications',
method: 'POST',
headers: headers,
}
const https = require('https')
const req = https.request(options, res => {
res.on('data', data => {
info(JSON.parse(data))
return callback(null, JSON.parse(data))
})
})
req.on('error', e => {
return callback({
message: e,
})
})
req.write(JSON.stringify(data))
req.end()
}
here is the notification controller folder
notification.controller.js
const { ONE_SIGNAL_APP_ID } = require('../utils/config')
const notificationsService = require('../services/notifications.services')
const sendNotification = (req, res, next) => {
const message = {
app_id: ONE_SIGNAL_APP_ID,
headings: { en: 'All Devices' },
contents: { en: 'Send push notifications to all devices' },
included_segments: ['All'],
content_available: true,
small_icon: 'ic_notification_icon',
data: {
// eslint-disable-next-line quotes
PushTitle: "Porc'Ivoire",
},
}
notificationsService.sendNotification(message, (error, results) => {
if (error) {
next(error)
}
return res.status(200).send({
message: 'Success',
data: results,
})
})
}
const sendNotificationToDevice = (req, res, next) => {
var message = {
app_id: ONE_SIGNAL_APP_ID,
headings: { en: '🤑 Paiement accepté' },
contents: {
en: 'Votre paiment a été effrctué avec succès',
},
included_segments: ['included_player_ids'],
include_player_ids: req.body.devices,
content_available: true,
small_icon: 'ic_notification_icon',
data: {
// eslint-disable-next-line quotes
PushTitle: "Porc'Ivoire",
},
}
notificationsService.sendNotification(message, (error, results) => {
if (error) {
next(error)
}
return res.status(200).send({
message: 'Success',
data: results,
})
})
}
module.exports = {
sendNotification,
sendNotificationToDevice,
}

MongoDB values being stored as null when using fetch in React

I've followed MongoDB's 'How To Use Mern Stack' tutorial to the letter, but I'm still getting null values stored in MongoDB. The console.log in the code does not appear, so I'm struggling to debug what's going on. Here's my code:
Client side
async function onSubmit(e) {
e.preventDefault();
// When a post request is sent to the create url, we'll add a new record to the database.
const newPerson = { ...form };
await fetch("http://localhost:5000/record/add", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newPerson),
}).catch((error) => {
window.alert(error);
return;
});
setForm({ name: "", position: "", level: "" });
navigate("/");
}
Server side
recordRoutes.route("/record/add").post(function (req, response) {
console.log("hi");
let db_connect = dbo.getDb();
let myobj = {
name: req.body.name,
position: req.body.position,
level: req.body.level,
};
db_connect.collection("records").insertOne(myobj, function (err, res) {
if (err) throw err;
response.json(res);
});
});
Thanks for your help!

API call works with Postman, but does not with Axios

I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request

Firebase cloud messaging: Request contains an invalid argument

I'm following this tutorial, I got to the point to send an HTTP request to the fcm endpoint, but I'm getting the following error:
{
error:
{
code: 400,
message: 'Request contains an invalid argument.',
status: 'INVALID_ARGUMENT'
}
}
Instead of sending the request using curl I'm using a cloud function using node.js | express with the following code:
exports.messages = function (req, res) {
const api = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send';
const headers = {
'Accept': 'application/json',
'Content-type': 'application/json',
};
return getAccessToken().then((accessToken) => {
headers.Authorization = `Bearer ${accessToken}` // <-- accessToken is OK
const { title, body, token } = req.body;
return fetch(api, {
headers,
method: 'POST',
body: JSON.stringify(
{
'message': {
'token': token, // <-- this is the client fcm token
'notification': {
'title': title,
'body': body
}
}
}
)
}).then(res => res.json()).then(data => {
console.log(data);
res.sendStatus(200);
}).catch((error) => {
console.error(error);
});
});
}
Where the token is an OAuth 2 token for my service account
function getAccessToken() {
return new Promise(function (resolve, reject) {
var key = require('../keys/service-account.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
[
'https://www.googleapis.com/auth/firebase',
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/firebase.messaging',
],
null
);
jwtClient.authorize(function (err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
what am I missing here? any advice will be appreciated
I just realized I copied the uri for the fcm endpoint from the tutorial. I changed it to:
const api = 'https://fcm.googleapis.com/v1/projects/{project-Id}/messages:send';
and it worked!

Unable to send button template as response on Facebook Messenger Platform (Node.js)

I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: {
access_token: Config.FB_PAGE_TOKEN
},
headers: {
'Content-Type': 'application/json'
},
});
const fbMessage = (recipientId, msg, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
text: msg,
},
},
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.
const fbInfo = (recipientId, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
attachment:{
type:"template",
text:"Check out our website",
payload:{
template_type:"button",
buttons:[
{
type:"web_url",
url:"https://some.website.com",
title:"Website"
}
]
}
}
}
}
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
Instead of form you should use json.
take a look at the code which I have written on glitch
should be something like:
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: <TOKEN> },
method: 'POST',
json: messageData}, ...)

Resources