Angular 4 - 在每个请求上设置 withCredentials - cors cookie [英] Angular 4 - setting withCredentials on every request - cors cookie
问题描述
我的 Angular 客户端与后端分离,我在后端启用了 cors,一切正常,除了我的身份验证失败,因为 cookie 未添加到请求中.
My angular client is separated from the backend and I have enabled cors on the backend, everything works fine except the fact that my authentication fails because the cookie is not added to requests.
在网上搜索后,我发现我应该在每个 http 请求上设置 {withCredentials : true}
.我设法针对单个请求执行此操作,并且可以正常工作,但无法针对所有请求执行此操作.
After searching online I found that I should set {withCredentials : true}
on every http request. I managed to do it on a single request and it works, but not on all the requests.
我尝试使用 BrowserXhr 如何发送Cookie"在 Angular2 中所有请求的请求标头中? 但它不起作用,而且它也被弃用了.
I tried using BrowserXhr How to send "Cookie" in request header for all the requests in Angular2? but it doesn't work and it's also deprecated afaik.
我也尝试过 RequestOptions,但没有奏效.
I also tried RequestOptions but it didn't work.
如何在每个 http 请求上设置 {withCredentials: true}
?
What can I do to set {withCredentials: true}
on every http request?
后期
@Injectable()
export class ConfigInterceptor implements HttpInterceptor {
constructor(private csrfService: CSRFService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.csrfService.getCSRF() as string;
const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
return next.handle(credentialsReq);
}
}
推荐答案
您可以使用 HttpInterceptor
.
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor() {
}
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 {}
这篇关于Angular 4 - 在每个请求上设置 withCredentials - cors cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!