angular 2 http withCredentials

Lin*_*rom 40 angular2-services angular2-http angular

我正在尝试使用withCredentials将cookie发送到我的服务但无法找到如何实现它.文档说"如果服务器需要用户凭据,我们将在请求标头中启用它们"没有示例.我尝试了几种不同的方法,但它仍然不会发送我的cookie.到目前为止,这是我的代码.

private systemConnect(token) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-CSRF-Token', token.token);
    let options = new RequestOptions({ headers: headers });
    this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
    .subscribe(uid => {
        console.log(uid);
    });
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*nov 52

尝试像这样更改您的代码

let options = new RequestOptions({ headers: headers, withCredentials: true });

this.http.post(this.connectUrl, <stringified_data> , options)...

如您所见,第二个参数应该是要在三分之一参数中发送(使用JSON.stringify或仅'')和所有选项的数据.

  • 由于HttpClient是标准,现在已经过时了 (3认同)

Ale*_*xei 13

从Angular 4.3开始,引入了HttpClient和Interceptor.

一个简单的例子如下所示:

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

constructor(
      private http: HttpClient) {

this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
    .subscribe(result => {
        this.forecasts = result;
    },
    error => {
        console.error(error);
    });
Run Code Online (Sandbox Code Playgroud)


Jam*_*ose 5

创建一个的Interceptor主意是将东西注入整个应用程序的头文件中。在另一方面,如果你正在寻找一个快速的解决方案,要对每个请求的级别进行的需要,尝试设置withCredentialstrue如下

const requestOptions = {
 headers: new HttpHeaders({
  'Authorization': "my-request-token"
 }),
 withCredentials: true
};
Run Code Online (Sandbox Code Playgroud)