我的角度客户端与后端分离,我在后端启用了cors,一切正常,但我的身份验证失败,因为cookie未添加到请求中。
在线搜索后,我发现我应该在每个http请求上设置{withCredentials : true}
。我设法在一个请求上执行它并且它可以工作,但不是在所有请求上。
我尝试使用BrowserXhr How to send "Cookie" in request header for all the requests in Angular2?,但它不起作用,它也被弃用了afaik。
我也尝试了RequestOptions但它没有用。
如何在每个http请求上设置{withCredentials:true}?
稍后编辑:
@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);
}
}
答案 0 :(得分:36)
您可以使用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 {}
答案 1 :(得分:2)
另一种可能更简单的方法是创建自己的 ApiService 。它将使用注入的HttpClient
。所有XHR请求都将直接使用ApiService而不是HttpClient。
这是一个示例实现:
我修改过的一些代码:
@Injectable()
export class ApiService {
private httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true // to allow cookies to go from "https://localhost:4567" to "http://localhost:5678"
};
constructor(
private http: HttpClient
) { }
private formatErrors(error: any) {
return throwError(error.error);
}
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { params })
.pipe(catchError(this.formatErrors));
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
this.httpOptions
).pipe(catchError(this.formatErrors));
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body),
this.httpOptions
).pipe(catchError(this.formatErrors));
}