我正在创建一个用于身份验证的节点API,在我的节点API中,我创建了一个登录会话并存储它。现在的问题是它在邮差很好,但在浏览器中,它不起作用。我假设它有一个cookie设置问题,在节点中是新的请给我一个适当的建议这个问题。我已经给出了代码。
在app.js中以这种方式设置快速会话。
app.use(session({ secret: 'middesecrectcode', resave:false, saveUninitialized:true }))
在我的API路线中,我已经做到了。
router.post('/testlogin', function(req, res, next){
req.session.username = "midde";
res.send("Your session has been created as "+ req.session.username);
req.session.success = true;
});
router.get('/checkSession', function(req, res, next){
console.log(req.session.success);
if(req.session.username){
res.send("hello "+req.session.username);
}
else{
res.send("session is not SET");
}
});
router.get('/logout', function(req, res, next){
req.session.destroy(function(err){
if(err){
console.log("Some error received when to logout");
}
res.send("You have got logged out successfully");
});
});
在浏览器中,我按以下方式调用API
的login.html
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type='text/javascript' src="login.js"></script>
</head>
<body>
<div>
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" id="uname">
</br>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="pwd">
</br>
<button id="btn" type="submit">Login</button>
</div>
<div>
<button id="btnSession" type="submit">Check Session</button>
</div>
</body>
</html>
login.js
$(document).ready(function(){
$("#btn").click(function(){
var uname = $("#uname").val();
var pwd = $("#pwd").val();
var dataSet = {
"username" : uname,
"password": pwd
}
var data2send = JSON.stringify(dataSet)
console.log(data2send);
$.ajax({
url: "http://localhost:8080/api/testLogin",
type: "post",
data: data2send,
contentType: 'application/json',
success: function(d) {
alert(d);
}
});
});
$("#btnSession").click(function(){
$.ajax({
url: "http://localhost:8080/api/checkSession",
type: "get",
contentType: 'application/json',
success: function(d) {
alert(d);
}
});
});
});
答案 0 :(得分:0)
我认为您的问题在于您在res.send
之前调用req.session.success = true;
。
在发送回复之前,请确保您已完成所有工作。尝试交换这样的行:
router.post('/testlogin', function(req, res, next){
req.session.username = "midde";
req.session.success = true;
res.send("Your session has been created as "+ req.session.username);
});