My GET, POST rquests works fine when there is no set headers in interceptors. If I do setHeaders in interceptors to set my userId data, 2 things I can see in Network tab:
- No response headers are seen which was visible earlier
- CORS error and 'Provisional headers are show' tag in the api request
Code (Interceptor)
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// return next.handle(apiRequest);
this.spinnerServcie.requestStarted();
const user_id = this.loginService.userDetails["user_id"];
if (!(user_id === undefined || user_id === null || user_id === '')) {
request = request.clone({
headers: request.headers.set( 'userId', user_id.toString())
});
}
return next
.handle(request)
.pipe(tap((event) => {
if (event instanceof HttpResponse) {
this.spinnerServcie.requestEnded();
}
},
(error: HttpErrorResponse) => {
this.spinnerServcie.resetSpinner();
throw error;
}));
It worked fine for GET, but fails for POST. Also I am using HTTPClient only for the request
CodePudding user response:
Http headers are not for sending data such as userId
. You must add them in params
(GET methods) or in body
(POST methods) to send them to server. see examples below:
GET:
this.http.get<MyResponseModel>('https://api.com/my-get-method', {params:{userId: '1'}});
POST:
this.http.post<MyResponseModel>('https://api.com/my-post-method', {userId: '1'});
Or set it in interceptor like this:
const constantBodyParams: any = {};
constantBodyParams.userId = 1;
req = req.clone({
body: {...req.body, ...constantBodyParams}
});