我正在使用angular 2(不是最新的使用通过angular-cli:1.0.0-beta.11-webpack.9-4),我必须为每个http请求设置withCredentials为true。我尝试使用
为一个请求设置它http.get(' http://my.domain.com/request',{withCredentials:true})
并且一切正常但是我正在尝试使用bootstrap中的内容,如下所示但没有取得任何成功
import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';
import {Http, Headers, BaseRequestOptions, RequestOptions, BrowserXhr} from '@angular/http';
if (environment.production) {
enableProdMode();
}
export class MyRequestOptions extends BaseRequestOptions {
constructor () {
super();
this.headers.append('withCredentials','true');
}
}
platformBrowserDynamic().bootstrapModule(AppModule,
[{ provide: RequestOptions, useClass: MyRequestOptions}]
);
答案 0 :(得分:3)
我不知道是否需要它,但我遇到了同样的问题而且我已经用这种方式解决了:
创建BaseRequestOptions的子类(扩展RequestOptions):
import { Headers, BaseRequestOptions } from "@angular/http";
export class AuthRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.withCredentials = true;
}
}
在应用程序引导程序中注册
import { RequestOptions } from '@angular/http';
import { AuthRequestOptions } from './<path>/AuthRequestOptions';
@NgModule({
bootstrap: [...],
imports: [...],
providers: [
{ provide: RequestOptions, useClass: AuthRequestOptions},
...
]
}...
(在我的情况下,这适用于CORS + NTLMAuthentication)
答案 1 :(得分:0)
如Sierrodc
所示,Angular 4.3+允许拦截器使用来配置它。与NTLMAuthentication一起使用的完整示例如下所示:
拦截器
@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
模块配置(拦截器允许与其他拦截器堆叠):
@NgModule({
imports: [CommonModule, BasicRoutingModule, HttpClientModule],
declarations: [HomeComponent, CounterComponent, FetchDataComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: WithCredentialsInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: BaseUrlInterceptor,
multi: true
}
]
})
export class BasicModule { }
实际使用情况
constructor(
private http: HttpClient) {
this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
.subscribe(result => {
this.forecasts = result;
},
error => {
console.error(error);
});
}