【问题标题】:Get JSESSIONID value and create Cookie in AngularJS获取 JSESSIONID 值并在 AngularJS 中创建 Cookie
【发布时间】:2016-01-04 14:27:51
【问题描述】:

我在 AngularJS 中使用来自客户端的 Web RestFUL API。

app.controller('LoginController', [
    '$http',
    '$cookies', 

    function($http, $cookies) {
      this.credentials = {};

      this.http = $http;

      this.login = function() {
        console.log(this.credentials);

        var authdata = btoa(
            this.credentials.username +
            ':' +
            this.credentials.password
        );

        $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;

        console.log($http);

        var res = $http.post("http://API_NAME/library");

        res.success(function(data, status, header){
            alert('Successfull func');

            console.log($cookies.get('JSESSIONID'));
        });

        res.error(function(data, status, headers, config) {
            console.log('Error Log');
        });
     };
   },
]);

然后,我有这个 Http headers 响应

Set-Cookie:JSESSIONID=azekazEXAMPLErezrzez; Path=/; HttpOnly

我正在使用 ngCookies 获取 JSESSIONID 值,然后在我的浏览器中手动创建它,但我无法访问它。

我已经在 StackOverflow 中看到了所有关于此的帖子,但它们已被弃用或完全不清楚。

感谢您的关注和帮助。

【问题讨论】:

  • 为什么需要在 Angular 中访问 JSESSIONID?该cookie被标记为HttpOnly,即在JS中无法访问。
  • 我没有得到自动处理cookie JSESSIONID 的发送。我以为我必须手动完成。评论帮助我理解了这一点。问题解决

标签: javascript angularjs http cookies


【解决方案1】:

您无法使用 JavaScript 获取 HttpOnly cookie。这就是 HttpOnly 标志的全部目的。

也就是说,您不需要这样做。 cookie 应随任何请求自动发送到同一服务器。如果您正在处理跨域 XHR 请求,请将 your_XHR_instance.withCredentials 设置为 true 以包含 cookie。

【讨论】:

  • XMLHttpRequest.withCredentials?由于它是一个 JavaScript 对象,因此很难在服务器端设置它。
  • 谢谢!我只需要在 app.config 中设置: $httpProvider.defaults.withCredentials = true;在我的 RestFUL 服务器上检查“Access-Control-Allow-Origin”是否正确设置并且“Access-Control-Allow-Credentials”设置为 true。它工作正常。感谢您的帮助:)
猜你喜欢
  • 2016-02-03
  • 2016-02-11
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多