Node.js 在路由内的代码之前执行公共模块?
我在nodejs中创建了一个公共模块,我在route中使用该公共模块,我想向所有用户发送通知。现在的问题是,当我首先调用route时,执行公共模块,然后执行route中的代码,但我想要的是执行第一个route代码,然后执行公共模块 这是路线,noti是通用模块Node.js 在路由内的代码之前执行公共模块?,node.js,mongodb,mongoose,ejs,Node.js,Mongodb,Mongoose,Ejs,我在nodejs中创建了一个公共模块,我在route中使用该公共模块,我想向所有用户发送通知。现在的问题是,当我首先调用route时,执行公共模块,然后执行route中的代码,但我想要的是执行第一个route代码,然后执行公共模块 这是路线,noti是通用模块 router.post('/', session, noti, async (req, res) => { const dt = dateTime.create(); const formatted1 = dt.format('Y
router.post('/', session, noti, async (req, res) => {
const dt = dateTime.create();
const formatted1 = dt.format('Y-m-d H:M:S');
try {
const str = req.body.providerId;
const data = str.split("|");
const id = data[0];
const name = data[1];
const date = req.body.resultDate;
const digit = req.body.winningDigit;
const exist = await ABgameResult.findOne({ providerId: id,resultDate: date,session: req.body.session });
if (!exist) {
const details = new ABgameResult({
providerId: id,
providerName: name,
resultDate: date,
winningDigit: digit,
status: 0
});
const savedGames = await details.save();
const update1 = await ABgamesProvider.updateOne(
{_id : id },
{ $set: { providerResult: digit, modifiedAt: formatted1,resultStatus : 1 } });
//resultStatus : 1 i.e; result is declared
const Resultid = savedGames._id;
const listData = {
providerId : id,
resultDate : date,
status: 0,
winningDigit: digit,
resultId: Resultid,
providerName: name
}
return res.json({
status : 1,
message : "Success",
data: listData
});
}
else {
const data = 'Details Already Filled For : '+ name +', Session : ' + req.body.session + ', Date: ' + req.body.resultDate;
res.json(data);
}
}catch (e) {
console.log(e);
res.json(e);
}
});
现在我想要的是当路由中的else部分被执行时,noti模块不应该被执行,我只想在代码的if部分执行它
这是noti的模块
module.exports = async function ( req, res,next) {
try
{
const token = await user.find({ banned : 1, andarBaharNotification: true }, {firebaseId : 1});
let userToken = [];
for(index in token){
userToken.push(token[index].firebaseId);
}
const digit = req.body.winningDigit;
const str = req.body.providerId;
const data = str.split("|");
const name = data[1];
var message = new gcm.Message({
priority: 'high',
data: {
title: " ("+name+")",
icon: "ic_launcher",
body: digit
}
});
sender.send(message, { registrationTokens: userToken }, function (err, response) {
if (err) console.error('error => ' ,err);
else console.log('response=> ',response);
});
next()
}
catch (e) {
console.log(e);
res.status(400).json({
status: 0,
message: 'Something Happpend',
error: e
});
}
};
我想你想这么做
const noti = require('./noti'); // importing noti
router.post('/', session, async (req, res) => {
// DO YOUR STUFF
noti(req, res);
});
从noti模块中删除
next()
。首先,路由器的右括号在哪里。post?在路由器的末尾,我还有一个问题,这是在nodejs中编写代码的正确方法吗?这是许多方法之一。在这个特定的例子中,我认为代码没有任何问题。