本文介绍了使用Socket.io快速4路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Express 4路线中添加Socket.io的时间非常粗略。在我的routes / index.js中,我有:

Having a rough time adding Socket.io in my Express 4 Routes. In my routes/index.js I have:

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

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

router.post('/message', function(req, res) {
  console.log("Post request hit.");
  // res.contentType('text/xml');
  console.log(appjs);
  io.sockets.emit("display text", req);
  // res.send('<Response><Sms>'+req.body+'</Sms></Response>');
});

module.exports = router;

但io未定义。我已经看到了几个如何做到这一点的例子,但没有一个对我有用。任何帮助将不胜感激。

but io is undefined. I have seen several examples of how to do this, but none that worked for me. Any help would be appreciated.

推荐答案

您需要将socket.io变量传递给路由器模块,以便它具有访问权限。您可以通过在函数调用中包装模块来完成此操作。

You need to pass your socket.io variable to the router module so that it has access. You could do this by wrapping your module in a function call.

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

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

    router.post('/message', function(req, res) {
        console.log("Post request hit.");
        // res.contentType('text/xml');
        console.log(appjs);
        io.sockets.emit("display text", req);
        // res.send('<Response><Sms>'+req.body+'</Sms></Response>');
    });

    return router;
}

module.exports = returnRouter;

然后,当您导入此路线时,您将调用此函数,如: require (./routefile)(io)

Then, whever you import this route you would call this function like: require(./routefile)(io)

这是一篇关于创建需要传递变量的模块的好文章:

Here's a good article about creating modules that require being passed a variable: Node.Js, Require and Exports

这篇关于使用Socket.io快速4路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:28