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!
Related
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,
}
i have this fetch request which send some body data to http://localhost:8000/report and then redirects to the same route on server to display data after processing :
const handleGo = async () => {
const employee = {
name: name.current.value,
month: month.current.value,
year: year.current.value,
};
await fetch("http://localhost:8000/report", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(employee),
});
window.location.replace("http://localhost:8000/report");
};
index.json server
const client = require("#jsreport/nodejs-client")("http://localhost:8001");
app.post("/report", (req, res, next) => {
employee.getEmpReport(req, res, next, client);
});
function getEmpReport
const getEmpReport = async (req, res, next, client) => {
const { name, month, year } = req.body; /// processing body data coming from react client
Employee.aggregate([
// doing some MongoDB join with conditions and returning results
]).exec(function (err, employee) {
const dataObject = {
/// setting some data from returned employee
};
client
.render({
template: { name: "/salary/salarySlipTemplate" },
data: dataObject,
options: { reports: { save: true } },
})
.then((response) => response.pipe(res))
.catch(next);
});
};
i want this route to process data and then display data after processing, but when window.location.replace("http://localhost:8000/report"); redirects to the route it says cannot get /report
i think i need a get route but then how can i recieve body data ? i want to be able to recieve the data from client and display it at the same time, how can i do that ?
i should send request from client to jsreport client and send data directly, server should only return the filtered employee:
import jsreport from "#jsreport/browser-client";
jsreport.serverUrl = "http://localhost:8001";
const handleGo = async () => {
const employee = {
name: name.current.value,
month: month.current.value,
year: year.current.value,
};
const response = await fetch("http://localhost:8000/report", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(employee),
});
const data = await response.json();
const report = await jsreport.render({
template: {
name: "/salary/salarySlipTemplate",
},
data: data,
});
report.openInWindow({ title: "salary slip" });
};
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?
I am writing Test case using JEST in NodeJs inside AzureFunction.
Im trying to mock JWT module outcome inside my index.test.js , however its not working and getting timedout. I wonder is it the return datatype mismatch? How to set response similar to cb of jwt verify method?
Here is my sample code. Please suggest!
Index.js
const JWT = require('./jwtDecoder')
module.exports = function(context, req) {
try {
JWT(req.body, process.env.jwtsecret, function(err, decoded) {
if (err) {
context.log("Invalid JWT::" + req.body);
context.res = {
headers: {
'Content-Type': 'application/json'
},
status: 400,
body: {
"error": err
}
};
context.done();
} else {
context.log("JWT Authentication Successful:");
context.res = {
headers: {
'Content-Type': 'application/json'
},
status: 200,
body: {
"message": "success"
}
};
context.done();
}
});
} catch (err) {
context.log("Exception in main function, PushHttpFunction:" + err);
context.res = {
headers: {
'Content-Type': 'application/json'
},
status: 500,
body: {
"error": err
}
};
context.done();
}
}
jwtDecoder.js
'use strict';
module.exports = (body, secret, cb) => {
console.log('inside jwtDecoder');
if (!body) {
return cb(new Error('invalid jwt data'));
}
require('jsonwebtoken').verify(body.toString('utf8'), secret, { algorithm: 'HS256' }, cb);
};
index.test.js
let indexTest = require('../index')
const { runStubFunctionFromBindings } = require('stub-azure-function-context')
let JWT = require('../jwtDecoder')
jest.mock("../jwtDecoder.js")
/* verify.mockImplementation(() => () => ({
err: new Error('invalid jwt data'),
decoded: 'ok'
})); */
JWT.mockImplementation(() => new Promise(function(resolve, reject) {
resolve('ok');
}));
beforeAll(() => {
process.env = Object.assign(process.env, {
NODE_ENV: "test",
});
});
describe('Simple Testing', () => {
test('return 200 by mocking simpleFunc response" ', async() => {
let request = {
body: "dummy.jwt.zT5p"
};
const context = await runStubFunctionFromBindings(indexTest, [
{ type: 'httpTrigger', name: 'req', direction: 'in', data: request },
{ type: 'http', name: 'res', direction: 'out' },
], new Date());
console.log('mockedResp::', context);
expect(context.res.status).toEqual(200);
}, 30000);
});
Basically you are mocking wrong, you can keep only this line:
jest.mock('./jwtDecoder.js', () => (res, req, cb) => cb(null, 'ok'))
as you need to mock callback
and remove all this part:
jest.mock("../jwtDecoder.js")
JWT.mockImplementation(() => new Promise(function(resolve, reject) {
resolve('ok');
}));
I'm building a crypto tracker in node. I have a list of addresses in the Wallet collection. I'm wanting to perform an API call to ethplorer for each address. I'm getting the error UnhandledPromiseRejectionWarning and also req.next is not a function. I'm confused because I'm not even using a req.next anywhere.
Any idea what's causing this error?
app.get('/ethplorer', function(req, res) {
const rp = require('request-promise');
Wallet.find({}).then(function(wallets) {
var allData = [];
wallets.forEach(function(w) {
const requestOptions = {
method: 'GET',
url: `https://api.ethplorer.io/getAddressInfo/${w.address}`,
qs: {
'apiKey': 'aaa'
},
json: true
};
rp(requestOptions).then(response => {
allData.push(response);
}).catch(function(err) {
console.log(err);
});
res.render('ethereum', {user: req.user, eth: allData});
});
});
});
allData is not going to be populated, nor should you do res.render in a loop
Rewritten to use async/await, avoid then() callbacks its messy
const rp = require('request-promise')
app.get('/ethplorer', async function (req, res, next) {
try {
const requestOptions = {
method: 'GET',
qs: {
'apiKey': 'aaa'
},
json: true
}
let allData = []
for (let wallet of await Wallet.find({})) {
try {
allData.push(await rp({
...requestOptions,
url: 'https://api.ethplorer.io/getAddressInfo/' + wallet.address
}))
} catch (_) {}
}
res.render('ethereum', {
user: req.user,
eth: allData
})
} catch (e) {
next(e)
}
})