Angular 拦截器不发送响应 header
Angular Interceptor do not send response header
我的 GET,POST rquests 在拦截器中没有设置 headers 时工作正常。
如果我在拦截器中执行 setHeaders 来设置我的 userId 数据,我可以在网络选项卡中看到两件事:
- 未看到响应 headers,之前可见
- CORS 错误和 api 请求中的 'Provisional headers are show' 标记
enter image description here
代码(拦截器)
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;
}));
它对 GET 工作正常,但对 POST 失败。此外,我仅将 HTTPClient 用于请求
Http headers 不用于发送 userId
等数据。您必须将它们添加到 params
(GET 方法)或 body
(POST 方法)中以将它们发送到服务器。请参阅以下示例:
获取:
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'});
或者在拦截器中这样设置:
const constantBodyParams: any = {};
constantBodyParams.userId = 1;
req = req.clone({
body: {...req.body, ...constantBodyParams}
});
我的 GET,POST rquests 在拦截器中没有设置 headers 时工作正常。 如果我在拦截器中执行 setHeaders 来设置我的 userId 数据,我可以在网络选项卡中看到两件事:
- 未看到响应 headers,之前可见
- CORS 错误和 api 请求中的 'Provisional headers are show' 标记
enter image description here
代码(拦截器)
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;
}));
它对 GET 工作正常,但对 POST 失败。此外,我仅将 HTTPClient 用于请求
Http headers 不用于发送 userId
等数据。您必须将它们添加到 params
(GET 方法)或 body
(POST 方法)中以将它们发送到服务器。请参阅以下示例:
获取:
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'});
或者在拦截器中这样设置:
const constantBodyParams: any = {};
constantBodyParams.userId = 1;
req = req.clone({
body: {...req.body, ...constantBodyParams}
});