express-session not saving nodejs

≯℡__Kan透↙ 提交于 2020-08-10 06:50:30

问题


This simple example is not working. In every request the session is created again, I don't know how to solve it.

var express = require('express'),
    expressSession = require('express-session'),
    app = express();

app.use(expressSession({
    secret:'secret',
    resave:true,
    saveUninitialized:true,
    cookie:{
        httpOnly:false,
        expires:false
    }
}));

app.all('/',function(req,res,next){
    var session = req.session;
    if(session.count){
        session.count++;
    }
    else{
        session.count = 1;
    }
    console.log('id:',req.sessionID);
    console.log('count:',session.count);
    res.end();
});

app.listen(9090);
console.log('server is running at http://localhost:9090');

I tried to save the count of requests, but the session is created every time when i make a request.

//request
>GET http://localhost:9090

//response
id: gOqbVisxaW34qafRdb7-6shqYV0UurRg
count: 1


//request again
>GET http://localhost:9090

//response
id: P2iyXKHElJF8u86tHu7mIl7Encteebju
count: 1

回答1:


I solved the problem, i made requests from other origins and with ajax. i added the following middleware on server:

app.use(function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader('Access-Control-Allow-Credentials', 'true');
            // Pass to next layer of middleware
            next();
        });

and in ajax request i put an option withCredentials in xhrFields

 $(document).ready(function(){
            setInterval(function(){
                $.ajax({
                    url:'http://localhost:9090/',
                    type:'post',
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    },
                    xhrFields:{
                        withCredentials:true
                    }
                });
            },1000);
        });


来源:https://stackoverflow.com/questions/34324460/express-session-not-saving-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!