我遇到了与 this 完全相同的问题问题,但对于 Angular 2。
总而言之,当向另一个域发送 HTTP 请求时,即使正确设置了 CORS header ,JSESSIONID cookie 也不会一起发送。 Angular 1.x 的解决方案是设置如下配置:
.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
但是我找不到 Angular 2 的任何替代解决方案。
有什么想法吗?谢谢!
最佳答案
您需要扩展默认的 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]
}
]
关于angularjs - $httpProvider.defaults.withCredentials 的 Angular2 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184049/