0

我对这个node.js世界很陌生。我正在尝试编写 REST 服务,但我被会话管理困住了。所以我创建了一个单独的应用程序只是为了看看我是否可以让会话工作,但它没有,这里是代码。req.session.username始终未定义:

var express = require('express');
var url = require('url');

var app = express()
app.use(express.cookieParser('Hiren'))
app.use(express.session({ secret: 'HirenAdesara' }))
app.use(express.bodyParser())
app.use(app.router)

//Sniff HTTP
app.all('*', function(req, res, next) {
    //Check for Authentication
            console.log(req.session)
    if ((!(/^\/auth/g.test(req.url))) && (!req.session)) {
        console.log('in app.all: Unauthorized')
        res.send(401)
    }
    else
    {
        return next()
    }
})

app.post('/auth', function(req, res) {
                var query =  req.body
                console.log('Query' + JSON.stringify(query))
                username = query.username;
                password = query.password;
                if(username == 'Hiren' && password == 'Adesara')
                {
                    req.session.username = 'Hiren';
                    console.log('New Session Created..')
                    res.send(200)
                }
                else
                {
                    console.log('New session could not be created.')
                    res.send(401)
                }
})

app.get('/projects', function(req,res) {
    console.log('inside projects' + req.session.username);
    res.send(req.session.username); })

app.listen(2048)
console.log('Listening on port 2048...')

它不起作用,我不知道这里有什么问题。

4

1 回答 1

3

通过将 app.get('/'...) 中的 3 行移到它之外来加注星标:

var express = require('express');
var querystring = require('querystring');

var app = express()
app.use(express.cookieParser('Hiren'));   // This line
app.use(express.session({ secret: 'HirenAdesara' })); // This line
app.use(express.bodyParser()); // This line

app.get('/', function(req, res){
   res.send('hello from the root page');
})

// the rest of your code
于 2013-03-25T18:11:43.140 回答