每次HttpClient调用时,Angular 6将withCredentials设置为true [英] Angular 6 set withCredentials to true with every HttpClient call

查看:213
本文介绍了每次HttpClient调用时,Angular 6将withCredentials设置为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果希望凭据(cookie身份验证令牌)可通过调用传递,则需要在httpclient调用中添加{ withCredentials: true }.像这样:

If you want the credentials (cookie authentication token) to be passable through a call, you need to add { withCredentials: true } in your httpclient call. Something like this:

import { HttpClient  } from '@angular/common/http';
...
constructor(private httpclient: HttpClient) { }

this.httpclient.get(url, { withCredentials: true })

我只想知道是否有一种方法可以在每次调用时预设{ withCredentials: true }.我不想每次打电话时都添加{ withCredentials: true }.

I would just like to know if there is a way to preset { withCredentials: true } with every single call. I don't want to have to add { withCredentials: true } every time I make a call.

这是一个相关的问题,但是我不确定这是否适用于HttpClient?

Here is a related question, but I am not sure if this works with HttpClient?

推荐答案

创建HttpInterceptor

@Injectable()
export class CustomInterceptor implements HttpInterceptor { 

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

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

        return next.handle(request);
    }
}

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}

这篇关于每次HttpClient调用时,Angular 6将withCredentials设置为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆