我正在尝试在node.js / express FW中建立一个包含用户数据的会话。 我正在使用快速会话。我还没有使用会话存储。 我在客户端(角度)中有2个页面在其中进行迭代-登录和仪表板。这个想法是在成功登录后创建会话,然后路由到仪表板页面。在仪表板页面中,我有一个带有routinlink的锚点:
<a [routerLink]="['/login']" >BackToLogin</a>
当导航回loginPage时(激活路由时),我执行一个带有到Express Server端点的服务,该服务检查请求中是否包含与请求的会话(我希望是)。 问题是我看到该会话不是同一会话(ID更改)
请参阅我的代码: Node.js端-server.js文件:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const session = require ('express-session');
var cookieParser = require('cookie-parser');
const SESS_NAME = 'sid';
app.use(session({
name:SESS_NAME,
key: 'user_sid',
resave:false,
saveUninitialized:false,
secure: process.env.NODE_ENV ==="production",
secret:'<some random text>',
cookie:{
httpOnly: true,
secure: process.env.NODE_ENV ==="production",
expires: 60000
}
}));
app.use(bodyParser.text());
app.use(bodyParser);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors()); //No limitation for test reasons
app.use(cookieParser());
//disabled on purpose
//var sessionManagement = require('./middleware/sessionManagement');
// API
app.use("/", require("./api/v1/routes.js"))//This file includes:
/*
const express = require('express');
const router = express.Router();
router.use("/login", require('./login'));
router.use("/session", require('./session'));
module.exports = router;
*/
...etc
app.listen(config.port, () => console.log(`Process ${process.pid}: Listening on port ${config.port}`));
服务器上的login.js:负责验证用户并在会话中存储用户数据:
const express = require('express');
const router = express.Router();
const schema = require('./objectSchemaJson.schema.json');
const scehmaCheck = require('../../middleware/checkForSchema')(schema);//this is
a schema check (middleware) - if suceeded continue (next)
const storeSession = (req, dataResult) =>
{
if (<dataResult return with valid use data>) //This is "where the magic happanes"
{
req.session.user = {
username: <get userName from dataResult>,
ID: <Get ID from dataResult>,
Role: <Get Role from dataResult>
}
}
}
router.use("/", scehmaCheck, (req, res, next) => {
return GetUserDataFROmDB(req.body).then((dataResult) => { //reaching the DB - not mentioned here on purpose
storeSession(req, dataResult); // This is where the session set with user data
res.status(200).json(dataResult);
}).catch((err) => {
next({
details: err
})
});
});
module.exports = router;
这是服务器上负责获取会话的端点-session.js-这是问题所在-res.session的会话ID与我在会话之后创建的ID不同。登录
const express = require('express');
const router = express.Router();
hasSession : function(req, res) //This is where the problem appears - the res.session has a session ID which is different that the one I created after the login
{
if (req.session.user)
{
res.status(200).json(
{
recordsets: [{Roles: req.session.Roles, UserName: req.session.user.username}]
});
}
else{
res.status(200).json({});
}
}
router.use("/", (req, res, next) => { return sessionManagement.hasSession(req, res, next)});
module.exports = router;
客户端:
//HTML:
<div>
<label>Username:</label>
<input type="text" name="username" [(ngModel)]="userName" />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" [(ngModel)]="password"/>
</div>
<div>
<button (click)="login()">Login</button>
</div>
//COMPONENT:
login()
{
this.srv.login(this.userName, this.password).subscribe(result =>
{
if (<result is valid>)
{
this.router.navigate(['/dashboard']);
}
}
);
}
//This reach the node.js endpoint and routing to the session.js end point - it is executes when the router-outlet activated in the app.component:
/*
onActivate(componentRef : any)
{
if (componentRef instanceof LoginComponent)
{
componentRef.getSession();
}
}
*/
getSession() : void
{
this.sessionService.getSession().subscribe( result =>
{
if (<result is valid>)
{
this.router.navigate(['/dashboard']);
}
});
}
我在github上发现了类似的问题-尚无解决方案: https://github.com/expressjs/session/issues/515 但这可能是Cookie <->服务器配置问题。
答案 0 :(得分:0)
发现了问题-根本原因是客户端在进行httprequest时未发送cookie。 解决问题需要完成2件事: 1.将CORS定义设置为“ creadentials:true”以及源名称(客户端的主机名,可能与其他端口\主机名不同): app.use(cors({ 来源:config.origin, 凭据:真实 })); 2.对于每个http rest方法(以我的情况为get和post),添加值为true的withCredentials属性: 返回this.http.get(,{withCredentials:true}) 要么 返回this.http.post(,,{withCredentials:true})