简体   繁体   English

如何在angularjs中的每个请求标头中发送cookie?

[英]How to send cookie in each request header in angularjs?

Hi I am in developing Angularjs web application. 嗨,我正在开发Angularjs Web应用程序。 I am using API's to get data. 我正在使用API​​来获取数据。 On login successful i will get some data in cookie(response header). 成功登录后,我将在cookie(响应头)中获取一些数据。 In very next subsequent http calls i need to send that back cookies data to apis. 在接下来的后续http调用中,我需要将这些cookie数据发送回api。 Below is the snapshot of response header. 下面是响应头的快照。

带有Cookie的响应头

Below is my sample $http call. 以下是我的示例$ http调用。

var req = {
              method: 'POST',
              url: savepersonaldetailsurl,
              headers: {
              RequestedPlatform: "Web",
              RequestedLanguage: cookiePreferredLanguage
              },
  data:      {
             LoginId: LoginID
             }
   $http(req).then(function (response) {
   //do something here
  }, function (error) {
     toastr.error($filter('translate')('Error Occured'));
     });

On each http call i want to send cookie in header. 在每个http调用中,我要在标题中发送cookie。 May i know how this can be done in angularjs? 我可以知道如何在angularjs中完成吗? Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。

One of the features of Cookies is that they're sent to the server with each request. Cookies的功能之一是随每个请求将它们发送到服务器。 Make sure that the domain the request is being made to is the same domain that set it or a sub domain. 确保将请求发送到的域是设置该请求的域或子域。

The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header - https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies Cookie通常由浏览器存储,然后将Cookie与在HTTP HTTP标头中的同一服务器的请求一起发送-https: //developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

First store the value which comes from response in localstorage then secondly you can make a common global functions which set the value to localstorage and get the value and call that function on every request. 首先,将来自响应的值存储在localstorage中,其次,您可以创建一个通用的全局函数,该函数将值设置为localstorage并获取该值,并在每次请求时调用该函数。

for example:- 例如:-

headers: {
    'Content-Type': 'application/json',
    'Authorization': authfunction.getToken('AuthToken');
}

In this example i set the value in local storage named AuthToken and while passing it we get and set it. 在此示例中,我在名为AuthToken的本地存储中设置了值,并在传递它的同时获取并设置了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM