【问题标题】:How to send cookies explicitly with GET request using AngularJs 1如何使用 AngularJs 1 通过 GET 请求显式发送 cookie
【发布时间】:2018-08-27 15:56:39
【问题描述】:

我正在使用 angularjs - 1.6。

我需要向服务器显式发送一个 http GET 请求和一个 cookie。

我的意思是,我知道一旦我们成功完成授权,cookie 就会随着每个 http 请求自动发送。

但就我而言,我需要明确发送。我怎样才能做到这一点。下面是https代码:

$cookies.put('JSESSIONID', 'lu5xxkdqgjk5qpv07ufhvln3');
 $http({
         url:"http://10.11.0.11:4440/api/21/projects",
          method:"GET",
          headers: { 'Accept': 'application/json',
                     'X-Rundeck-Auth-Token':'lu5xxkdqgjk5qpv07ufhvln3'},
         "Access-Control-Allow-Credentials" : true
      }).then(function(response) {
          $scope.response = response.data;
          alert("Report fot succeed"+response.data);
      }, function(response) {
          alert("error response:"+response.data);
      }); 

【问题讨论】:

  • 简单修改:headers: {'Cookie': 'your cookie value', 'Accept': ...}

标签: angularjs angular-http angular-cookies


【解决方案1】:

您可以通过多种方式做到这一点。

如果您坚持认为它应该是 GET,则可以将 cookie 的值作为标头之一发送:

headers: {'Cookie': 'Value', ...}

当然,您可以事先获取 cookie 的值,然后将其分配给某个变量,然后将 'Cookie' 标头设置为该值。

headers: {'Cookie': myVariable, ...}

记得设置

 $httpProvider.defaults.withCredentials = true;

.config 文件中。

如果要发送的数据比较复杂,您应该考虑将 GET 更改为 POST,因为提到了 POST 来发送数据,例如:

   this.login = function (loginInfo) {

        return $http({
            url: 'your url',
            headers: {
                'Content-Type' : 'your content type'
                // other headers..
            },
            method: 'POST',
            data: {
                user: {
                    name: loginInfo.nick,
                    password: loginInfo.password
                }
            }
        })
        .then(function(response) {
             console.log('success');
        });
   }

【讨论】:

  • 如果我在标头中设置 cookie,则会收到此错误:angular.min.js:108 Refused to set unsafe header "Cookie"
  • 你在配置中设置$httpProvider.defaults.withCredentials = true;了吗?
  • 你为什么不直接发送帖子,无论如何,从 cookie 的标题中发送数据对我来说似乎很奇怪,你在这个 cookie 中到底有什么?例如,如果您将令牌存储在此 cookie 中,也许您应该使用拦截器。
  • 您还应该将 angular.min.js 更改为 angular.js 以进行开发以查看更多描述性错误信息
猜你喜欢
  • 2020-01-24
  • 2021-09-20
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多