当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why won't req.session set with node.js

问题描述:

I can't seem to get set anything for

req.session

I'm trying to store oauth token and the secret into a session so i can check them after the authorize callback. Here is my code

var express = require('express'),

app = express(),

server = require('http').createServer(app),

io = require('socket.io').listen(server),

oauth = require('oauth'),

tumblr = require('tumblr.js'),

client = {

consumer_key: '1n9fMPxCBFBbcIGRImYKSK5wwDL6yux64S4DxEwiwzHTNuaIoD',

consumer_secret: 'bW9YKbnwgxexyVx1AaxQr1QoemEkjd29p5U1WpbZ8r1XEH41C0'

},

consumer = new oauth.OAuth(

"http://www.tumblr.com/oauth/request_token", "http://www.tumblr.com/oauth/access_token",

client.consumer_key, client.consumer_secret, "1.0A", "http://127.0.0.1:8080/sessions/callback", "HMAC-SHA1");

server.listen(1337);

app.configure('dev', function(){

app.use(express.logger());

app.use(express.bodyParser());

app.use(express.cookieParser());

app.use(express.session({ secret: "topsecret" }));

});

app.get('/home', function(req, res){

consumer.getOAuthRequestToken(function(err, oauth_token, oauth_token_secret, results){

if(err){

console.log(err);

}else{

//req.session.oauth.token = oauth_token;

console.log('oauth.token: ' + oauth_token);

//req.session.oauth.token_secret = oauth_token_secret;

console.log('oauth.token_secret: ' + oauth_token_secret);

res.redirect('http://www.tumblr.com/oauth/authorize?oauth_token='+oauth_token);

}

});

});

app.get('/oauth/testapp', function(req, res){

res.send('callback');

});

When I uncomment

req.session.oauth.token = oauth_token;

I get an error "cannot read property 'oauth' of undefined" also req.session displays undefined in the console.

网友答案:

You're trying to set the property token on an object oauth on the session. If the oauth object is not initialized, it will be undefined, and you can't set the token attribute. You first need to initialize the oauth object in the session. You could for instance do

req.session.oauth = {token: theToken}

This will create an object in the session and also set the token property of that object.

@robertklep figured out the other half of the solution: Make sure you're running with the correct environment. Since you have used dev in app.configure, you have to run node with NODE_ENV=dev for the configuration to be applied.

网友答案:
var app = express();
app.configure('dev', function() {
    app.use(express.logger());
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: "topsecret" }));
    app.use(app.router); // You need to add the router after the express.session
});

hope this can help you

分享给朋友:
您可能感兴趣的文章:
随机阅读: