我遇到与this问题完全相同的问题,但对于Angular 2。
总之,当向另一个域发送HTTP请求时,即使正确设置了CORS头,也不会发送JSESSIONID cookie。 Angular 1.x解决方案是设置以下配置:
.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
但是我无法找到Angular 2的替代解决方案。
有什么想法吗?谢谢!
答案 0 :(得分:1)
您需要扩展默认的Http服务并将withCredentials设置为true
http.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, Request, RequestOptions, Response, XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class HttpService extends Http {
constructor(backend: XHRBackend, options: RequestOptions) {
super(backend, options);
}
request(url: string | Request, options?: any): Observable<Response> {
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
options.withCredentials = true;
} else {
url.withCredentials = true;
}
return super.request(url, options);
}
}
http.service.factory.ts
import { RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './http.service';
export function HttpServiceFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
return new HttpService(backend, defaultOptions);
};
并在您的模块文件中,您需要替换您的http服务
import { HttpServiceFactory } from './http.service.factory';
import { Http, RequestOptions, XHRBackend } from '@angular/http';
...
providers: [
{
provide: Http,
useFactory: HttpServiceFactory,
deps: [XHRBackend, RequestOptions]
}
]
答案 1 :(得分:0)
当您从'@ angular / http'导入{Http,Response,Headers}使用Http服务时,您可以设置withCredentials:true;
post(params:string, obj:any): Observable<any> {
let headers = new Headers();
headers.append("content-type", "application/json");
return this.http.post(this.apiUrl + params, JSON.stringify(obj), { headers: headers, withCredentials: true })
.map((response : Response)=>{
return response.json();
});;
}