app.post('/user/signin',function(req,res){
var user=req.body.user;
var {name,password}=user;
User.findOne({name:name},function(err,user){
if(err) console.log(err);
if(!user) return res.json({state:1});
user.comparePassword(password,function(err,isMatched){
if(err) console.log(err);
if(isMatched) {
res.json({state:3});
}
else res.json({state:2});
});
});
});
$('#signinModal .btn-success').on('click',function(e){
$.ajax({
type:'POST',
url:'/user/signin',
data:$('#signinModal form').serialize(),
success:function(data){
switch(data.state){
case 1:$('#errorName').css({opacity:1});break;
case 2:$('#errorPassword').css({opacity:1});break;
case 3:location.href='/';break;
}
}
});
});
PHP中文网2017-04-17 15:34:28
You can assign user information to req.session.user through req.session.user = userInfo
When you jump to the homepage, you can get user information through req.session.user.
If your front-end page needs it, you can pass the value during rendering, such as
res.render('index',{
user: req.session.user
});
If you are using the express framework, you can use res.locals.user = req.session.user;
In this way, your page can be obtained directly by using the user variable, such as:
<p class="menu">
<% if (user) { %>
<a class="item" href="/posts?author=<%= user._id %>">个人主页</a>
<p class="pider"></p>
<a class="item" href="/posts/create">发表文章</a>
<a class="item" href="/signout">登出</a>
<% } else { %>
<a class="item" href="/signin">登录</a>
<a class="item" href="/signup">注册</a>
<% } %>
</p>
PHP中文网2017-04-17 15:34:28
(Take the java backend as an example) After the front-end ajax submits the form (var loader = new net.AjaxRequest(url, deal_data, onerror, "POST", params);
) [Note: net.AjaxRequest is a predefined function, where deal_data is the callback processing function after the ajax request is successful], the backend performs business After processing, use JSONArray to place the results to be returned, write httpservletresponse into it, and return it to the front end,
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, true);
response.getWriter().print(jsonArray);
Processed by the ajax callback function: get the return text, parse it into json data, and process it as needed.
var datas = eval(this.req.responseText);