我使用Express“express”:“~4.13.1”和“express-session”:“^ 1.11.3”。 我已经设置了我的服务器:
app.js:
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var routes = require('./routes/index');
var users = require('./routes/users');
app = express();
// view engine setup
var engines = require('consolidate');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Using express-session in app with secret key
app.use(session({
secret: 'mapdcs',
resave: true,
saveUninitialized: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: null
}
}));
app.use('/', routes);
app.use('/api/users', users);
index.js:
// First call
router.post('/adduser', function(req, res, next) {
req.session.username = red.body.username;
req.session.save();
console.log('>>Session data From Add users');
console.log(req.session); //I got the username session here
}
// Second call
router.post('/check_auth', function(req, res, next) {
console.log('>> Session data From check_auth');
console.log(req.session); //Am not getting session here.
}
自从过去两天以来我一直试图解决这个问题。请任何人帮忙。提前谢谢。
答案 0 :(得分:1)
您似乎错过了右括号')'路由器通话后,我不认为这是主要问题。它与请求没有正确发送响应/终止有关。
如果你将console.log(req.session)更改为发送响应的内容,例如res.json(req.session),则第二个调用有效 - 请参阅下面的示例:
router.post('/adduser', function(req, res, next) {
req.session.username = red.body.username;
req.session.save();
console.log('>>Session data From Add users');
// changed console.log to res.json
res.json(req.session)
}); // Added the final closing bracket to router.post
// Second call
router.post('/check_auth', function(req, res, next) {
console.log('>> Session data From check_auth');
// Changed the second console.log to res.json
res.json(req.session);
}) // Added another closing bracket
希望这有帮助!
编辑:您也可以使用res.end(),res.send()或res.render() - 生成响应的任何内容 - 请参阅Express response docs。
答案 1 :(得分:0)
我更改了axios调用,并将withCredential
设置为true
以解决该问题。