【问题标题】:Using $http.get to retrieve from API(zendesk) not working使用 $http.get 从 API(zendesk) 检索不起作用
【发布时间】:2016-04-09 22:46:03
【问题描述】:

我正在尝试对Zendesk's 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 

似乎运作良好。可能是显而易见的事情。

【问题讨论】:

  • 尝试将“withCredentials: true”添加到您的 $http 配置对象中。 docs.angularjs.org/api/ng/service/$http#usage
  • 另外,我不认为您的 curl 请求正在发送授权标头...也许 client.user + client.token 需要在请求正文中传递?
  • 很确定您的 Authorization 标头的值是错误的......用户名和密码必须用冒号连接(:),然后生成的字符串必须是 base64 编码 - 不是各个部分。

标签: javascript angularjs api curl


【解决方案1】:

问题是您需要正确设置授权标头,它们应该是 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 2018-05-20
    • 2022-12-25
    • 1970-01-01
    • 2014-12-27
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多