在路由文件中使用socket.io

时间:2018-02-28 23:45:44

标签: javascript node.js express websocket socket.io

我试图传递套接字并在路由文件中使用它们。

我正在导出 routes.js 模块

module.exports = function (client) {

  var express = require("express"); // call express
  var router = express.Router(); // get an instance of the express Router
  var admin = require("firebase-admin");

  router.use(function (req, res, next) {
    // do logging
    client.on('save-message', function (socket) { console.log("heheyy") })
  });
  router
    .route("/")
    .get(function (req, res, err) {

       ... route stuff...
      });
  router
    .route("/")
    .post(function (req, res, err) {
       ... route stuff
    });
}
//module.exports = router; **commented**

在我的 server.js 我包含路由模块然后我在套接字连接功能中使用它

var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var routerProj = require("./routes/routes");

var server = app.listen(port);
var io = require("socket.io")(server);
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');

  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
  next();
});
var config = {
  .... configuration
};
firebase.initializeApp(config);


var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://datatable-18f93.firebaseio.com"
});
app.use("/v1", routerProj, function (req) {
  //Create HTTP server and listen on port 8000 for requests


});
// Print URL for accessing server
console.log("Server running at http://127.0.0.1:8080/");
io.on("connection", function (client) {
  console.log("Un client est connecté !");
   routerProj(client);
});

当我将路径文件包装在模块函数中时,路由不起作用,不提取或插入数据。所以套接字也不起作用。

用于 server.js 文件

中的信息套接字

0 个答案:

没有答案