我是Node Js的新手。我正在使用socket.io和express创建应用程序,它在用户登录后获取推文。我如何创建会话,以便推文页面只能在登录后打开,而不能在没有登录的情况下打开。
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/login.html');
});
app.get('/tweets', function (req, res) {
res.sendfile(__dirname + '/twitter.html');
});
答案 0 :(得分:3)
配置Express
var app = express();
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', key: 'express.sid'}));
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
server = http.createServer(app)
server.listen(3000);
配置Socket.IO
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
if (handshakeData.headers.cookie) {
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
handshakeData.sessionID = connect.utils.parseSignedCookie(handshakeData.cookie['express.sid'], 'secret');
if (handshakeData.cookie['express.sid'] == handshakeData.sessionID) {
return accept('Cookie is invalid.', false);
}
} else {
return accept('No cookie transmitted.', false);
}
accept(null, true);
});
答案 1 :(得分:2)