使用Socket.io快速4路由

编程入门 行业动态 更新时间:2024-10-17 15:24:50
本文介绍了使用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)

这是一篇关于创建需要传递变量的模块的好文章: Node.Js,Require and Exports

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

更多推荐

使用Socket.io快速4路由

本文发布于:2023-10-31 13:24:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546210.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   快速   Socket   io

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!