【问题标题】:angularjs and googles url shortenerangularjs 和 google 的 url 缩短器
【发布时间】:2017-09-11 13:35:58
【问题描述】:

我目前在使用 google url 缩短器时遇到问题。 我已经设置了这个服务:

angular.module('widget.core').service('urlShortener', service);

function service($log, $q, $http) {

    var gapiKey = '<MyApiKey>';
    var gapiUrl = 'https://www.googleapis.com/urlshortener/v1/url';

    return {
        shorten: shorten
    };

    //////////////////////////////////////////////////

    function shorten(url) {
        console.log(url);
        var data = {
            method: 'POST',
            url: gapiUrl + '?key=' + gapiKey,
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                longUrl: url,
            }
        };

        return $http(data).then(function (response) {
            $log.debug(response);
            return response.data;
        }, function (response) {
            $log.debug(response);
            return response.data;
        });
    };
};

据我所知,这应该可行。我输入了正确的 API 密钥,当我运行这个方法时,我得到了这个错误:

{
    error: {
        code: 401,
        message: 'Invalid credentials'
    }
}

但是,如果我使用邮递员并完全按照这种方法进行设置:

当我发布此内容时,它可以正常工作。 我在 google 控制台上检查了我的应用程序,它肯定设置为无限制。

以前有人遇到过这个问题吗?有人知道怎么解决吗?

【问题讨论】:

    标签: javascript angularjs google-url-shortener


    【解决方案1】:

    我想通了,这与上面的代码无关,但我想我会回答我自己的问题,因为其他人可能会遇到同样的问题。

    在项目中,我有一个 httpInterceptor 设置,它将身份验证令牌添加到与我的 API 对话的每个请求中。这就是导致问题的原因。 碰巧我已经为我的 apiUrl 定义了一个常量,所以我刚刚更新了拦截器以检查以确保在尝试附加令牌之前请求 url 是我的 api。 像这样:

    angular.module('widget.core').factory('authInterceptor', factory);
    
    function factory($q, $location, $localStorage, apiUrl) {
    
        // The request function
        var request = function (config) {
    
            // If we are querying our API
            if (config.url.indexOf(apiUrl) > -1) {
    
                // Get our stored auth data
                var authData = angular.fromJson($localStorage.get('authorizationData'));
    
                // Set our headers to the request headers or a new object
                config.headers = config.headers || {};
    
                // If we have any auth data
                if (authData && authData.authenticated) {
    
                    // Set our authorization header
                    config.headers.Authorization = 'Bearer ' + authData.token;
                }
            }
    
            // Return our config
            return config;
        };
    
        return {
            request: request
        };
    };
    

    我希望这对其他人有所帮助。我花了几个小时才弄明白:/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 2019-12-13
      • 2021-04-24
      • 2011-08-20
      相关资源
      最近更新 更多