angular-ui替换'?'在从 facebook oauth 重定向时使用“#”

angular-ui replace'?' with '#' on redirect from facebook oauth

我正在 angularjs 中实现 facebook ouath 登录而无需 SDK。

除一件事外,一切都按预期工作。

当用户点击登录按钮时,重定向到 facebook 登录页面,成功登录后,facebook 触发 redirect_uri URL,用户再次进入应用程序。

问题是,ui-router(可能)替换了'?'路径中带有“#”,所以

http://localhost/fbauth?access_token=xxx&code=yyy
变成
http://localhost/fbauth#access_token=xxx&code=yyy

因此,我无法使用 $stateParams 获取带有查询参数的对象。

奇怪的是,当我在浏览器手动输入或者点击link http://localhost/fbauth?access_token=xxx&code=yyy
一切正常,并且 ui-router 不会替换 '?'用'#'。

我猜,这与重定向场景本身有关。

谁能指出我做错了什么,或者在这种情况下如何更改 ui-router 行为?

这是处理 fb 重定向的状态:

.state('fbauth', {
  url: '/fbauth?access_token&code&expires_in',
  templateUrl: 'static/public/public.html',
  controller: 'publicCtrl'
});

PS ui-路由器设置为在 html5 模式下工作 $locationProvider.html5Mode(true);

我不喜欢在客户端路由中传递查询参数(使用 ? 标记)。相反,您可以使用 route/state 参数,如下所示:

http://localhost/#/fbauth/access_token/:access_token/code/:code

并且您可以使用 $stateParams 访问这些值。例如($stateParams.access_token)

您可以将此解析函数添加到您的状态,它将用查询字符串 url:

替换散列 url
resolve: {
    'urlFix': ['$location', function($location){
        $location.url($location.url().replace("#","?"));
     }]
}
  • 因此 /fbauth#access_token=123456&code=abcde&expires_in=99999999 中的 url 会自动重定向
  • 成为/fbauth?access_token=123456&code=abcde&expires_in=99999999
  • $stateParams 将被正确填充。
  • 值为 {access_token: "123456", code: "abcde", expires_in: "99999999"}
  • 如果位置已经匹配,
  • $location.url() 不会更新,因此当 # 不存在时状态不会重定向。

完整示例代码:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
    <meta charset="utf-8">
    <title>FBAUTH</title>
</head>
<body ng-app="app">
    <base href="/">
    <div ui-view></div>
    <script>
        angular.module('app', ['ui.router'])
            .controller('publicCtrl', ['$scope','$stateParams', function($scope, $stateParams) {
                // $stateParams should be correctly set (even for hash route)
                console.log($stateParams);
            }])
            .config(['$locationProvider','$stateProvider', function($locationProvider, $stateProvider){
                $stateProvider
                    .state("fbauth",
                    {
                        url: '/fbauth?access_token&code&expires_in',
                        templateUrl: 'fbauth.html',
                        controller: 'publicCtrl',
                        resolve: {
                            'urlFix': ['$location', function($location){
                                $location.url($location.url().replace("#","?"));
                            }]
                        }
                    });

                $locationProvider.html5Mode(true);
            }]);
    </script>
</body>
</html>