简体   繁体   English

没有为Angular2发布请求设置响应中的Set-cookie

[英]Set-cookie in response not set for Angular2 post request

When I make a put request in Angular2, I receive the expected set-cookie in the response. 当我在Angular2中发出put请求时,我在响应中收到了预期的set-cookie。 However my browser (tried both Chrome and Firefox) refuses to set the cookie. 但是我的浏览器(尝试过Chrome和Firefox)都拒绝设置cookie。

Instead when I use an Angular 1 app making a call to the same API endpoint, the cookies are set correctly. 相反,当我使用Angular 1应用程序调用同一 API端点时,cookie被正确设置。

The response headers are: 响应标头是:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://example.com
Allow:GET, PUT, HEAD, OPTIONS
Content-Type:application/json
Date:Thu, 28 Jan 2016 14:41:38 GMT
P3P:policyref="http://www.example.com/p3p.xml", CP="NON DSP COR CURa TIA"
Server:WSGIServer/0.1 Python/2.7.6
Set-Cookie:sessionid=994wl49qfsizog5bqmt57sgx9q2toa25; expires=Mon, 28-Mar-2016 14:41:37 GMT; Max-Age=5183999; Path=/
Set-Cookie:csrf=u7UQhpAphTsGYKRU6jFlLFt6NoYAhNMS; Domain=api.example.com; expires=Thu, 26-Jan-2017 14:41:38 GMT; Max-Age=31449600; Path=/
Vary:Accept, Cookie

The backend is programmed in Django 1.8. 后端在Django 1.8中编程。

Does anyone experienced the same thing or have a suggestion how to solve this problem? 有没有人经历过同样的事情或有建议如何解决这个问题?

Indeed a CORS issue. 确实是一个CORS问题。 From Angular2 RC2 on, you just need to 从Angular2 RC2开始,你只需要

this.http.get('http://my.domain.com/request', { withCredentials: true })

I seems to be a CORS-related issue. 我似乎是一个与CORS相关的问题。 Perhaps you could try to set the withCredentials attribute when executing the HTTP request. 也许您可以在执行HTTP请求时尝试设置withCredentials属性。

This answer could help you to find out how to do that, especially the Cedric Exbrayat 's answer: 这个答案可以帮助你找到如何做到这一点,特别是Cedric Exbrayat的回答:

Edit 编辑

You could extend the BrowserXhr : 您可以扩展BrowserXhr

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = true;
    return <any>(xhr);
  }
}

and override the BrowserXhr provider with the extended: 并使用扩展名覆盖BrowserXhr提供程序:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

If you need more hints about CORS, you could have a look at this link: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/ . 如果您需要有关CORS的更多提示,可以查看以下链接: http//restlet.com/blog/2015/12/15/understanding-and-using-cors/

Hope it helps you, Thierry 希望它对你有帮助,蒂埃里

我有同样的问题,但对我来说,cookie有一个'/ api / order'的路径..所以只有请求到这个路径包含cookie ..我改变路径为'/',现在everthig很好..

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

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