Home > OS >  Node js error, "myFunction" is not a function
Node js error, "myFunction" is not a function

Time:05-05

So I am using the fcm-node package in order to send notifications from the Express api route to the app using a registration token.

The function is:

const FCM = require('fcm-node');
const serverKey = ...
const fcm = new FCM(serverKey);

function sendNotification(registrationToken, title, body, dataTitle, dataBody) {
    const message = {
        to: registrationToken,
        notification: {
            title: title,
            body: body
        },
        data: {
            title: dataTitle,
            body: dataBody
        }
    };

    fcm.send(message, (err, response) => {
        if (err) console.log('Error ', err)
        else console.log('response ', response)
    });
};

module.exports = {
    sendNotification
};

I made sure that if outside the function, the notification system is running. Now In the api endpoint:

const sendNotification = require('../sendNotification');

router.get('/test', async (req, res, next) => {
  sendNotification('...', 'hi', 'bye','1', '2');
  return res.send(200)
};

I keep on getting the error "sendNotification" is not a function. What is the cause of this?

CodePudding user response:

Expression require('../sendNotification'); is giving you a object (because you exported a object in this file), so extract what you need out.

const { sendNotification } = require('../sendNotification');

CodePudding user response:

try this:

module.exports = sendNotification

and use it like this:

const sendNotification = require('../sendNotification');
  • Related