Ionic/Cordova AngularJS getting request header of $http

时间:2015-10-29 15:58:23

标签: angularjs cookies ionic-framework ionic

I want to get the $http cookie request header after a request but the $http only returns a response according to the AngularJS documentation. Here is the cookie I want to get:

enter image description here

I tried adding an interceptor but I couldn't see the cookie. Here is the output from my interceptor:

enter image description here

My interceptor and some settings:

$provide.factory('myHttpInterceptor', function() {
      return {
        // optional method
        'request': function(config) {
          console.log(config);
          return config;
        }
      };
    });

    $httpProvider.interceptors.push('myHttpInterceptor');

    $httpProvider.defaults.useXDomain = true;
    //Remove text on back button
    $ionicConfigProvider.backButton.previousTitleText(false).text('  ');
    $httpProvider.defaults.withCredentials = true;
    //Setting angularjs' $http to behave as url encoded parameters and request instead of JSON
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

2 个答案:

答案 0 :(得分:1)

您无法在cordova应用中使用Cookie。 Stackoverflow中有很多其他帖子以及我在this blog上找到的最新信息,其中的问题在这些文字中说明:

  

我真的很喜欢科尔多瓦的一切,除了你不能使用基于cookie的会话。

在cordova中,您可以访问由html5引入的会话存储和本地存储。

http://www.w3schools.com/html/html5_webstorage.asp例如使用单词:

引入localstorage
  

HTML本地存储,优于cookie。

http://learn.ionicframework.com/formulas/localstorage/包含如下示例代码:

  

使用这个简单的AngularJS服务轻松设置和检索字符串或对象:

angular.module('ionic.utils', [])

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
       return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}]);
  

要使用此服务,只需将$ localstorage服务注入控制器或运行函数:

angular.module('app', ['ionic', 'ionic.utils'])

.run(function($localstorage) {

  $localstorage.set('name', 'Max');
  console.log($localstorage.get('name'));
  $localstorage.setObject('post', {
    name: 'Thoughts',
    text: 'Today was a good day'
  });

  var post = $localstorage.getObject('post');
  console.log(post);
});

现在,有了这个例子,你可以做类似的事情:

$localstorage.set('sessionId', 'yourSessionIdGoesHere');

并阅读

$localstorage.get('sessionId');

答案 1 :(得分:1)

如果您不介意我问,为什么要在客户端阅读JSESSIONID?

我可以想象你会想要在每次后续请求中发送它,但如果你使用withCredentials = true,那么它会自动为你完成。