【问题标题】:How to access token in response headers using Angularjs?如何使用Angularjs访问响应标头中的令牌?
【发布时间】:2016-09-22 20:28:36
【问题描述】:

我有以下代码使用 Ionic 2、angularjs 和 devise_token_auth 对用户进行身份验证,但如果登录成功,我会在响应的标头中收到访问令牌,而不是在 json 中。

authenticate(user) {
        var creds = "email=" + user.name + "&password=" + user.password;
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return new Promise(resolve => {
            this.http.post('http://localhost:3000/auth/sign_in', creds, {headers: headers}).subscribe(data => {
                if(data.json().data){
                    this.storeUserCredentials("MY TOKEN IN THE HEADER");
                    resolve(true);
                }
                else
                    resolve(false);
            });
        });
    }

但我开始研究 AngularJS 和 ionic。我不知道访问标头中的访问令牌

【问题讨论】:

  • 您是否尝试访问response.access_token?这对我有用。

标签: angularjs angular ionic-framework


【解决方案1】:

这就是我们可以从 $http 响应中访问响应头的方法。

$http.post('/api').then(function(response) {
     //Accessing header
     console.log(response.headers()['access-token']);
});

您的代码有点不同。你可以试试这个。

this.http.post('http://localhost:3000/auth/sign_in', creds, {headers: headers}).subscribe(data => {
            if(data.json().data){
                this.storeUserCredentials(data.json().headers()['access-token']);
                resolve(true);
            }
            else
                resolve(false);
        });

【讨论】:

    【解决方案2】:

    $scope.token=respone.headers('Authorization') 此行将从响应中返回令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2016-11-23
      • 2018-01-23
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多