我正在使用angular(前端)和node.js + express(后端)。当我在localhost:3000
(运行Express应用程序的端口)上运行我的应用程序时,一切都正确,并且即使刷新页面,我也注意到请求会话ID是相同的。但是,当我想在localhost:4200
上以开发人员模式工作时,该会话将不再持久,并且每次刷新页面时,都会显示一个新的会话ID。
app.js
const bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
cors = require('cors'),
express = require('express'),
session = require('express-session');
const app = express();
app.use(cors());
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(session({
secret: 'MY-KEY',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
server.listen(port, () => console.log(`API running on localhost:${port}`));
在开发模式下,我也在使用代理,如下所示:
proxy-conf.json
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
答案 0 :(得分:0)
找到它后,我必须:将localhost:4200
添加到白名单,在cookie.secure
中将false
设置为session
app.js
var whitelist = ['http://localhost:4200'];
var corsOptions = {
origin: function(origin, callback) {
if (whitelist.indexOf(origin) === -1) {
callback(new Error('Not allowed by CORS'));
} else {
callback(null, true);
}
},
credentials: true,
};
app.use(cors(corsOptions));
.
.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
.
.
app.use(session({
secret: 'My-Key',
resave: false,
saveUninitialized: true,
cookie: { secure: false },
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
,然后在每个Http请求标头中添加:
withCredentials: true
为
isLoggedIn(): Observable < boolean > {
return this.http.get(ip + 'api/isAuthenticated', { withCredentials: true }).map(response => response.json());
}