流程
- 点击登录按钮,前端把当前的url,传给后台
- 后台把url传给,登录页面
- 登录页面,点击登录,跳转到登录前的页面
效果
第一步
![clipboard.png clipboard.png](https://image-static.segmentfault.com/794/634/79463418-5c6d0cf7d0d53_articlex)
第二步
![clipboard.png clipboard.png](https://image-static.segmentfault.com/700/048/700048869-5c6d0d0e99833_articlex)
第三步
![clipboard.png clipboard.png](https://image-static.segmentfault.com/140/191/1401916562-5c6d0d2da1fe7_articlex)
router
router.get('/login', initMiddleware, controller.default.pass.login);
点击登录按钮
view
appviewdefaultpublicheader.html
<li><a href="javascript:void(0)" id="loginButton" target="_blank">登录</a></li>
apppublicdefaultjsbase.js
initLogin: function() {$("#loginButton").click(function() {// alert(location.href);location.href = '/login?returnUrl=' + encodeURIComponent(location.href);})}
controller
appcontrollerdefaultpass.js
async login() {//获取returnUrlvar returnUrl = this.ctx.request.query.returnUrl;returnUrl = returnUrl ? decodeURIComponent(returnUrl) : '/';await this.ctx.render('default/pass/login.html', {returnUrl: returnUrl});}
登录页面
appviewdefaultpasslogin.html
<input type="hidden" name="returnUrl" id="returnUrl" value="<%=returnUrl%>" />
$("#doLogin").click(function(e) {var returnUrl = $('#returnUrl').val();var username = $('#username').val();var password = $('#password').val();var identify_code = $('#identify_code').val();var reg = /^[\d]{11}$/;if (!reg.test(username)) {alert('手机号输入错误');return false;}if (identify_code.length < 4) {alert('验证码长度不合法');return false;}//ajax请求$.post('/pass/doLogin', {username: username,identify_code: identify_code,password: password}, function(response) {console.log(response);if (response.success == true) {// location.href = "/";location.href = returnUrl;} else {$("#identify_code_img").attr('src', '/verify?mt=' + Math.random());alert(response.msg);}})})
去结算的登录跳转
中间件
appmiddlewareuserauth.js
module.exports = (options, app) => {return async function init(ctx, next) {//判断前台用户是否登录 如果登录可以进入 ( 去结算 用户中心) 如果没有登录直接跳转到登录var userinfo = ctx.service.cookies.get('userinfo');var prevPage = ctx.request.headers.referer; //上一个页面的地址if (userinfo && userinfo._id && userinfo.phone) {//判断数据库里面有没有当前用户 var userResutl = await ctx.model.User.find({ "_id": userinfo._id, "phone": userinfo.phone });if (userResutl && userResutl.length > 0) {//注意await next();} else {// ctx.redirect('/login');ctx.redirect('/login?returnUrl=' + encodeURIComponent(prevPage));}} else {// ctx.redirect('/login');ctx.redirect('/login?returnUrl=' + encodeURIComponent(prevPage));}};
};
效果
![clipboard.png clipboard.png](https://image-static.segmentfault.com/134/848/1348484306-5c6d1346eedbc_articlex)
![clipboard.png clipboard.png](https://image-static.segmentfault.com/108/241/1082411644-5c6d134baa8a5_articlex)
![clipboard.png clipboard.png](https://image-static.segmentfault.com/375/214/3752149265-5c6d1353e0761_articlex)