如何从nodejs,express和socketio应用程序中的app.post启动会话,以便通过套接字连接可以使用会话中的用户ID?

时间:2018-10-03 11:44:50

标签: node.js express socket.io

我的套接字应用程序在iframe中打开,其中包含来自另一个应用程序的发布请求,该应用程序在请求数据中发送用户ID。我在app.post中获取了该用户ID,但是在路由会话时,我被重置了,并且无法在io.on下获取该用户ID来基于该用户ID检索数据。

app.js代码-

var crypto = require('crypto')
const http = require('https')
const express = require('express')
const cookieParser = require('cookie-parser')
const mysql = require('mysql')
const socket = require('./socket')
const routes = require('./routes')
var bodyParser = require('body-parser');
const { sessionMiddleware } = require('./middlewares')

var fs = require( 'fs' );   
var app = express();  

var options = {
  hostname: 'https://xxx.xxx.net:3000',
  key: fs.readFileSync('xxx.pem'),
  cert: fs.readFileSync('xxx.pem')  
};

const server = http.createServer(options,app)
const io = socket(server)

io.use((socket, next) => {
  sessionMiddleware(
      socket.request,
      socket.request.res,
      next
  ) 
})

app.use(sessionMiddleware)

app.use(express.static('public'))
app.use('/', routes)
app.use(cookieParser())

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
      Content-Type, Accept");
   next();
});

// parse application/json
app.use(bodyParser.json())

 app.post('/', function(req, res){  

   var uid = req.body.userid;
   req.session.userID = uid;
   req.session.save();
   console.log('data-'+req.session.userID);

    res.redirect('/home');  
 });


io.on('connection', socket => { 

    // need to get user id here
    //do all action here based on userid
    console.log('sessionTD-'+socket.request.sessionID);

    //const req = socket.request

})

0 个答案:

没有答案