簡體   English   中英

angularjs和google網址縮短器

[英]angularjs and googles url shortener

我目前與Google網址縮短器有問題。 我已經設置了此服務:

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控制台上檢查了我的應用程序,並且絕對將其設置為不受限制。

有人遇到過這個問題嗎? 有人知道如何解決嗎?

我知道了這一點,與上面的代碼無關,但是我想我會回答自己的問題,因為其他人可能會遇到相同的問題。

在項目中,我設置了一個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
    };
};

希望對您有所幫助。 花了我幾個小時才弄清楚:/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM