angular-ui替换'?' 从facebook oauth重定向'#'

Jar*_*ema 13 facebook oauth facebook-graph-api angularjs angular-ui-router

我正在没有SDK的angularjs中实现facebook ouath登录.

除了一件事,一切都按预期工作.

当用户点击登录按钮,重定向到Facebook登录页面,成功登录后,Facebook会激活redirect_uri URL,用户再次进入应用程序.

问题是,ui-router(可能)取代'?' 路径中带有'#',所以

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

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

因此,我无法使用$stateParams查询参数获取对象.

令人惊讶的是,当我手动进入浏览器或点击链接, 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'
});
Run Code Online (Sandbox Code Playgroud)

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

Sco*_*ott 5

您可以将此resolve函数添加到您的状态,该状态将使用查询字符串url替换哈希URL:

resolve: {
    'urlFix': ['$location', function($location){
        $location.url($location.url().replace("#","?"));
     }]
}
Run Code Online (Sandbox Code Playgroud)
  • 因此,网址/fbauth#access_token=123456&code=abcde&expires_in=99999999会自动重定向
  • 变得 /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>
Run Code Online (Sandbox Code Playgroud)