Html $http 不在请求中发送 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17064791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$http doesn't send cookie in Requests
提问by Tim Daubenschütz
We are working on a RESTful Webservice with AngularJS and Java Servlets.
When the user logs in, our backend sends a "Set-Cookie" header to the frontend. In Angular we access the header via $cookies
(ngCookie - module) and set it.
我们正在使用 AngularJS 和 Java Servlet 开发 RESTful Web 服务。当用户登录时,我们的后端向前端发送一个“Set-Cookie”标头。在 Angular 中,我们通过$cookies
(ngCookie - 模块)访问标头并设置它。
Now that the user is logged in he can for example delete some stuff. Therefore the frontend sends a GET request to the backend. Because we work on different domains we need to set some CORS Headers and Angular does an OPTIONS request before the actual GET request:
现在用户已经登录,他可以删除一些东西。因此,前端向后端发送 GET 请求。因为我们在不同的域上工作,所以我们需要设置一些 CORS 标头,而 Angular 在实际 GET 请求之前执行 OPTIONS 请求:
OPTIONS request:
选项请求:
GET request
获取请求
We do this in Angular via $http module, but it just won't send the cookie, containing JSESSIONID
.
我们通过 $http 模块在 Angular 中执行此操作,但它不会发送包含JSESSIONID
.
How can I enable Angular to send cookies?
如何启用 Angular 发送 cookie?
回答by Mathew Berg
In your config, DI $httpProvider
and then set withCredentials to true:
在您的配置中,DI$httpProvider
然后将 withCredentials 设置为 true:
.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
})
Info on angularjs withCredentials: http://docs.angularjs.org/api/ng.$http
关于 angularjs withCredentials 的信息:http://docs.angularjs.org/api/ng.$http
Which links to the mozilla article: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#section_5
哪些链接到 mozilla 文章:https: //developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale =en-US &redirectslug =HTTP_access_control#section_5
回答by Daniel F
$http.get("URL", { withCredentials: true })
.success(function(data, status, headers, config) {})
.error(function(data, status, headers, config) {});
Another thing to keep in mind: You need to have 3rd party cookies enabled. If you have it globally disabled in Chrome, click on the "i"-Symbol to the left of the domain name, then cookies, then "blocked" and unblock the target domain.
要记住的另一件事:您需要启用第 3 方 cookie。如果您在 Chrome 中全局禁用它,请单击域名左侧的“i”-符号,然后单击 cookie,然后单击“阻止”并取消阻止目标域。