我为后台创建了一个nodejs-expressjs
应用程序,并使用angularjs
作为首页。
在 nodejs (localhost:3000
)上,我使用:
在app.js(服务器端)上,我这样初始化cookieparser和session:
..
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4000");
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'app')));
app.use(session(
{
key: "mycookiesession",
secret: credentials.cookieSecret,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 900000, httpOnly: false }
}
)//session
);//app.use
business.auth = function(req,res){
if(!req.body.username || !req.body.password)
{
res.status(400);
res.send({status:'error',msg:'Username or password is missing.'});
}
var user = ownerModel.authUser(req.body.username, req.body.password, req.session.id);
user.then(function(user){
if(!_.isEmpty(user)){
req.session.username = user.username;//save username to session
req.session.ownerId = user.ownerId;//save ownerid to session
res.status(200);
res.json({status:'success',msg:'user logged n.',sessionId:req.session.id});
}else{
res.status(401);
res.json({status:'error',msg:'User doesn\'t exist.'});
}
}, function(){
res.json({status:'error',msg:'Error occured while fetching login data from database.'});
});
};
router.get('/:appId', helpers.isAuthenticated, products.list); // products:appId
products.list = function(req, res){
console.log('REQUEST TO GET PRODUCTS (productsController)');
var prod = productModel.list(req.params.appId);
prod.then(function(products){
res.send(products);
}, function(){
res.send({status:'error',error:'Error occured while fetching data from database.'});
});
};
我使用' restangular
'模块向服务器发出请求。这很好用,它会发送凭据并登录。
问题1 :登录后,当我在浏览器上打开新标签来调用产品时(来自角度),localhost:4000/#/products/5
它会发送不同的sessionid,我得到的不是授权'以及session.username
&我之前在登录时指定的session.ownerId
,现在尚未定义
问题2 :它不稳定,有时会话(当呼叫产品/ 5时)是相同的并且它提取产品但是大多数时候它没有。
邮递员:当我使用 postman 时,它会运行登录,产品和订单等,但我会调用服务器URL,如下所示:localhost:3000/business/auth, localhost:3000/products/5
等。
我应该保存sessionid的某个地方吗?在每次请求时,不应始终从客户端向服务器发送相同的sessionid?我应该将sessionid从服务器发送到客户端吗?