尝试在路由内使用带有socket.io的发出事件

时间:2018-10-03 21:29:27

标签: node.js express socket.io

我正在尝试使用socket.io在路由内部发出事件。我的路线在另一个创建通知的文件中 而我的app.js在我的根目录中,该根目录与socket.io 我已经读过有关将其变成函数调用的信息...但是我正在了解如何使用它。

这是我的app.js

var express = require("express");
var app = express();
var middleware = require("./middleware/index.js");
var bodyParser = require("body-parser");
var passport = require("passport");
var LocalStrategy = require("passport-local");
var mongoose = require("mongoose");
var flash = require("connect-flash");
var Book = require("./models/book");
var User = require("./models/user");
var Review = require("./models/reviews"); // comment
var Reserve = require("./models/reserve.js");
var Notification = require("./models/notification.js");
var User = require("./models/user");
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var notifTest = require('./event/returnRouter')(io);


var methodOverride = require("method-override");


//requiring routes
var reviewRoutes = require("./routes/reviews");
var bookRoutes = require("./routes/books");
var indexRoutes = require("./routes/index");
var reserveRoutes = require("./routes/reserve");

//====================================================
app.set('socketio', io);
mongoose.connect("mongodb://localhost:27017/library", { useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
app.locals.moment = require('moment')

//====================================================
// Passport Config
//====================================================
app.use(require("express-session")({
    secret: "HICCUP!!",
    resave: false,
    saveUninitialized: false
}));


app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());



//====================================================
//
//====================================================
app.use(async function(req, res, next){
   res.locals.currentUser = req.user;
   if(req.user) {
    try {
      let user = await User.findById(req.user._id).populate('notifications', null, { isRead: false }).exec();
      res.locals.notifications = user.notifications.reverse();
    } catch(err) {
      console.log(err.message);
    }
   }
   res.locals.error = req.flash("error");
   res.locals.success = req.flash("success");
   next();
});

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect("/login");
    }
}

app.use("/", indexRoutes);
app.use("/library/:id/reviews",reviewRoutes);
app.use("/library",bookRoutes);
app.use("/library/:id/reserve", reserveRoutes);




io.on('connection', function(socket){
  console.log('a user connected');

  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});



//====================================================
//Library Server Start
//====================================================

server.listen(process.env.PORT, process.env.IP, function() {
    console.log("Library server has started");
    console.log("Listening at PORT: " + process.env.PORT);
})

,然后是一个函数调用文件。 returnRouter.js

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

/* GET home page. */
var returnRouter = function(io) {


    router.post('/message', function(req, res) {
        io.sockets.on('news', function (data) {
    console.log(data);
    io.sockets.emit('my other event', { my: 'data' });
  });
    });

    return router;
}
module.exports = returnRouter;

最终...我希望能够在路线中发出事件,因此当我按下按钮时,它会更新我的通知...

reserve.js

    router.post("/", middleware.isLoggedIn,  async function(req, res) {
    //lookup book using id
    // console.log("this is available " + req.body.available);
    var username = req.user.username;
    var userId = req.user._id;
    var available = req.body.available;
    var daysToAdd = 2;
    var id = '5b70bb0f58e4610cf8181b92';
    var reservedBy = {username: username, userId: userId, available: available};
// ===============================================================================
    try {
        let book = await Book.findById(req.params.id);
        let reserve = await Reserve.create(reservedBy);
        // let user = await User.findById(req.user._id).populate('followers').exec();
        let user = await User.findById(id).exec();

        reserve.returnDate = reserve.borrowDate.setDate(reserve.borrowDate.getDate() + daysToAdd);
        reserve.reserved.id = reservedBy.userId;
        reserve.reserved.username = reservedBy.username;
        reserve.save();

        book.reserves.push(reserve);
        if (book.available < 1) {
            req.flash("error", "There are no more available books");
            res.redirect("/library/" + book._id);
        } else {
            book.available--;
            await book.save();
            res.redirect("/library/" + book._id); 
        }

        let newNotification = {
            username:req.user.username,
            bookId: book.id,
            bookName: book.name
        }


        let notification = await Notification.create(newNotification);
        user.notifications.push(notification);
        user.save();


    } catch(err) {
      req.flash('error', 'Something went wrong!');
      res.redirect('back');
    }
});

1 个答案:

答案 0 :(得分:0)

路线:

const Router = require('express').Router

const router = new Router();

router.get('/my-route', (req, res, next) => {
    console.log(req.app.locals.io) //io object
    const io = req.app.locals.io
    io.emit('my event', { my: 'data' }) //emit to everyone
    res.send("OK")
});

module.exports = router

主文件:

const app = require('express')()
const server = require('http').Server(app);
const io = require('socket.io')(server)
const myroute = require("./route") //route file dir

app.use(myroute);

server.listen(3000, () => {
    console.log('¡Usando el puerto 3000!');
});

app.locals.io = io