使用$http.get从API(zendesk)检索不起作用

Using $http.get to retrieve from API(zendesk) not working

本文关键字:zendesk 检索 不起作用 API http get 使用      更新时间:2023-09-26

我正在尝试对Zendesk的API进行API调用,并且我一直得到401验证代码,即使当我在终端中执行cURL时,同样的事情也有效。如何在Angular中完成此工作?

function dataservice($http) {
    var service = {
        getMacros: getMacros
    };
    return service;
    /////////////////////
    function getMacros() {
        var client = {
           username: window.btoa('myEmail'),
           token: window.btoa('/token:myToken'),
           remoteUri: 'https://myCompany.zendesk.com/api/v2/macros.json'
        };
        console.log('Loading...');
        return $http({
               method: 'GET',
               url: client.remoteUri,
               headers: {
                   'Authorization': client.username + client.token
              }
            })                
            .then(getMacrosComplete)
            .catch(function (message) {
                exception.catcher('Failed to getMacros')(message);
            });
        function getMacrosComplete(response) {
            console.log('Done');
            var data = response.data;
            return data;
        };
    };

上面的代码总是返回401,而这是有效的:

curl myEmail/token:myToken https://myCompany.zendesk.com/api/v2/macros.json 

看起来效果不错。可能是显而易见的。

问题是您需要正确设置Authorization标头,它们应该是Base64编码的,并且您必须声明"基本"身份验证(这是大多数人错过的主要部分)。

所以这应该有效:

function dataservice($http) {
    var service = {
        getMacros: getMacros
    };
    return service;
    /////////////////////
    function getMacros() {
        var client = {
           username: 'myEmail',
           token: 'myToken',
           remoteUri: 'https://myCompany.zendesk.com/api/v2/macros.json'
        };
        console.log('Loading...');
        return $http({
               method: 'GET',
               url: client.remoteUri,
               headers: {
                   'Authorization': 'Basic ' + window.btoa(client.username + '/token:' + client.token)
              }
            })                
            .then(getMacrosComplete)
            .catch(function (message) {
                exception.catcher('Failed to getMacros')(message);
            });
        function getMacrosComplete(response) {
            console.log('Done');
            var data = response.data;
            return data;
        };
    };

当然,您必须在Zendesk帐户中启用令牌身份验证,否则您可以通过用户+密码进行身份验证,方法是设置密码并执行以下操作:

'Authorization': 'Basic ' + window.btoa(client.username + ':' + client.password)