[英]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'
}
}
但是,如果我使用邮递员并完全按照以下方法进行设置:
将主体设置为:
{longUrl:'myreallylogurl.com'}
当我发布此消息时,它没有任何问题。 我已经在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.