POST请求后执行模块

Ped*_*les 5 javascript push-notification node.js express

我正在尝试通过套接字(使用socket.io)集成发送实时信息,并使用OneSignal平台发送推送通知.

碰巧的是,如果我把所有东西放在同一个模块中,我不知道为什么在发送信息之后或发送信息之前不会执行发送通知的方法.

如果我运行命令npm start没有出现错误,但是一旦本地或远程服务器运行,通知就会到达,这样我就不希望它发生了.

user.js的

  var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');
var notificacion = require('../routes/notificacion');

/*

run module when start server run, i don't want it

notificacion();

*/ 

/* GET users listing. sendnote*/
router.post('/sendasig', function(req, res, next) { 


    console.log(misocket);//registrednote
    misocket.emit("registrar",req.body);  
  //run here, after the send data across post request
  notificacion();
    console.log(req.body);

  res.status(200).json({
      message  : "send message"
  }); 

});

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

notificacion.js

 module.exports = function(){ 

        var OnesignalNotificationApi = require('onesignal-notification');
        var api = new OnesignalNotificationApi('N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3',
                                        'c4b92cce-4d59-4550-a4be-20939370e39c');

        var message = {
                it: 'Some message',
                en: 'Some message',
                es: 'Nueva Calificacion'
        };

        api.sendToAll(message, null, function(err, res){
                console.log(err);
                console.log(res);
        }); 

}; 
Run Code Online (Sandbox Code Playgroud)

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

misocket.js

var i = 0;
var ioapp;

exports.connection= function(io){

    ioapp = io;

    io.on('connect',function(s){
        console.log("Conectado");    
    });

};

exports.io = ioapp;
Run Code Online (Sandbox Code Playgroud)

Sha*_*ool 1

在您的 notification.js 文件中,当需要该文件时(这可能是在您运行时),将执行 sendToAll 函数。

api.sendToAll(message, null, function(err, res){
    console.log(err);
    console.log(res);
}); 
Run Code Online (Sandbox Code Playgroud)

您需要将其包装在一个函数中并在您的帖子路由中调用它。

module.exports = function(message){ 
  api.sendToAll(message, null, function(err, res){
     console.log(err);
      console.log(res);
   }); 
}
Run Code Online (Sandbox Code Playgroud)

然后可以在服务器顶部需要它

 const sendMessageFunction = require('path/to/notification.js')
 .
 .
 .
 sendMessageFunction('helloWorld')
Run Code Online (Sandbox Code Playgroud)