【问题标题】:Angular Interceptor do not send response headerAngular Interceptor 不发送响应标头
【发布时间】:2021-12-11 17:57:51
【问题描述】:

当拦截器中没有设置标头时,我的 GET、POST 请求可以正常工作。 如果我在拦截器中使用 setHeaders 来设置我的 userId 数据,我可以在 Network 选项卡中看到两件事:

  1. 没有看到之前可见的响应标头
  2. CORS 错误和 api 请求中的“显示临时标头”标记

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 用于请求

【问题讨论】:

  • 请不要将您的代码发布为图像,因为如果他们必须从图像中键入您的解决方案而不是仅仅复制代码,则更难复制。

标签: angular angular-http-interceptors python-django-storages


【解决方案1】:

Http 标头不适用于发送userId 等数据。您必须将它们添加到params(GET 方法)或body(POST 方法)中才能将它们发送到服务器。请参阅以下示例:

获取:

this.http.get<MyResponseModel>('https://api.com/my-get-method', {params:{userId: '1'}});

发布:

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}
});

【讨论】:

  • 但是我想为所有请求添加它,所以我使用了拦截器。
  • 我可以这样添加吗? request = request.clone({body: {...request.body, userId: user_id.toString()}});
  • 是的,类似的。我会更新答案。 @Charmi
  • 成功了。谢谢@skyBlue
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2019-06-20
  • 2018-10-27
  • 2018-02-04
  • 1970-01-01
  • 2023-04-01
  • 2018-10-03
相关资源
最近更新 更多