简体   繁体   English

如何在连接时通过nodeJS将PHP变量或会话传递给socket.io

[英]How do i pass a PHP variable or session through nodeJS to socket.io on connection

I'm currently building a chat for my website which is built in PHP with MongoDB. 我目前正在为我的网站建立一个聊天室,该聊天室使用PHP和MongoDB构建。

When the user Logs in i create Session variables for the user but can't seem to find a way to pass that variable through nodejs to socket.io. 当用户登录时,我为用户创建了Session变量,但似乎找不到找到将变量通过nodejs传递给socket.io的方法。

I use this in the chat html page 我在聊天html页面中使用它

var socket = io('http://localhost:3000', { query: *I need my php information here* });

Ajax defeats the purpose and is too slow. Ajax无法达到目的,而且速度太慢。

Notes: i know i can pass with ajax on message but i'd prefer to pass on connection. 注意:我知道我可以通过ajax传递消息,但是我更喜欢传递连接。

Im using this code in my server.js which makes it impossible for it to be .php file 我在我的server.js中使用此代码,这使其不可能成为.php文件

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

You could pass your PHP information in a global Javascript variable. 您可以在全局Javascript变量中传递PHP信息。 Something like 就像是

<script>var phpInfo = "<%= $yourInfo =>"</script>

( here the <%= stand for <?php echo "" ?> ) (这里<%=代表<?php echo "" ?>
You can then use this variable into your connection 然后,您可以在连接中使用此变量

var socket = io('http://localhost:3000', { query: phpInfo });

This is not optimal but it works, Another way you could do that is retreive your info at some point (either then the user connect or when you load the main page) and save this into the HTML5 localStorage using window.localStorage.setItem('phpInfo', phpinfo) and then access this data using window.localStorage.getItem('phpInfo') 这不是最佳方法,但它可行。另一种方法是在某个时候检索信息(然后用户连接或在加载主页时),然后使用window.localStorage.setItem('phpInfo', phpinfo)将其保存到HTML5 localStorage中window.localStorage.setItem('phpInfo', phpinfo) ,然后使用window.localStorage.getItem('phpInfo')访问此数据
This is a more elegent way to do it. 这是一种更优雅的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM