节点js错误,"myFunction"不是一个函数

Node js error, "myFunction" is not a function

所以我正在使用 fcm-node 包,以便使用注册令牌从 Express api 路由向应用程序发送通知。

函数是:

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
};

我确定如果在函数之外,通知系统是运行。现在在 api 端点:

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

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

我一直收到错误“sendNotification”不是函数。这是什么原因?

试试这个:

module.exports = sendNotification

并像这样使用它:

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

表达式 require('../sendNotification'); 正在给你一个对象(因为你在这个文件中导出了一个对象),所以提取你需要的东西。

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