且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单页应用程序与登录页面深度链接

更新时间:2023-02-08 17:39:07

我决定使用方法2:该应用只有1页,登录页面将是使用javascript来回切换的应用程序中的视图。。我发现这不难做,我仍然可以使用正常的基于cookie的身份验证与服务器上的会话,成功登录后将用户重定向到默认页面(主页面)等等。这是一个示例代码,我如何使用angularjs。

I decided to go with approach 2: The app has only 1 page and the login page will be a view in the app which is switched back and forth using javascript.. I found out that it's not difficult to do and I can still use normal cookie-based authentication with session on server, redirect users to default page (main page) after successful login, and so on. Here is a sample code how I do it with angularjs.

路由:

var App = angular.module('App', ["ui.state"]);

App.config(function ($stateProvider, $routeProvider) {
   $stateProvider.
   .state('login', {
        url: "/login?returnUrl",
        templateUrl: '/Home/Login',
        controller:"LoginController"
    })
    .state('main', {
        url: "/main",
        abstract:true,
        templateUrl: '/Home/Main',
        controller: "MainController"
     })
})
.run(function ($rootScope, $state, $stateParams, $location) {
     $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ 
        if (error.status == 401) {
            $state.transitionTo("login", { returnUrl: $location.url() });
        }
     })
});

这里的意思是当状态401(从服务器)发生路由更改错误时,表示用户没有登录,我将使用返回URL转换到登录状态。

The point here is when there is a route change error with status 401 (from the server) indicating that the user is not logged in, I will transition to login state with the return url.

用户使用ajax成功登录后,我将把状态转回我的主视图。这样做:

After the user successfully logging in using ajax, I will transition the state back to my main view. Something like this:

$http.post("/Login", JSON.stringify({UserName:username,Password:password}))
     .success(function (data, status, headers, config) {
        var returnUrl = $stateParams.returnUrl ? $stateParams.returnUrl : "mydefaulturl";
        $location.url(returnUrl);
 })

使用这种方法,现在我可以创建深度链接到我的应用程序中的特定状态,并登录页面并返回url。

With this approach, now I'm able to create deep-link to jump to a specific state in my app with login page and return url.