You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular拦截器中创建HttpHeaders失效问题求助

问题:HttpHeaders创建失效排查

我需要为拦截器传递新的HttpHeaders配置,原因是认证流程中我的API不接受Authorization请求头。我尝试了克隆请求、删除Authorization头以及直接创建新HttpHeaders的方式:

const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            userId: StorageUtil.getUserId().toString(),
            marinaId: StorageUtil.getMarinaId().toString(),
            token: StorageUtil.getMarinaIntegrationKey()})
        }

所有StorageUtil相关方法均正常工作,但日志中显示lazyInit仅包含一个name为空的空对象。我还尝试了使用.append()、.set()方法:

const httpOptions = {
     headers: new HttpHeaders().set('Content-Type', 'application/json')
                               .set('userId', StorageUtil.getUserId().toString())
                               .set('marinaId', StorageUtil.getMarinaId().toString())
                               .set("token", StorageUtil.getMarinaIntegrationKey())
            };

但结果出现lazyUpdate相关内容,问题仍未解决。以下是我的拦截器代码:

intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    this.token = StorageUtil.getToken();
    const header = request.headers['lazyUpdate'];

    if (this.token && this.token !== '') {
      if (
        request.url.indexOf('easyworkshop') > 0 ||
        request.url.indexOf('localhost') > 0 ||
        request.url.includes('192.168.25')
      ) {
        let headers = new HttpHeaders({
          Authorization: 'Bearer ' + this.token,
          marinaId: '' + StorageUtil.getMarinaId(),
          userId: '' + StorageUtil.getUserId(),
          integrationKey: '' + StorageUtil.getMarinaIntegrationKey(),
          OriginEasy: 'EasyWeb',
          'Access-Control-Allow-Origin': '*',
          'Content-type': 'application/json',
        });
        if (header && header.length > 0) {
          const contentTypes = header.filter(
            (x) => x.name === 'Content-Type' || x.name === 'Accept'
          );
          if (contentTypes.length > 0) {
            headers = new HttpHeaders({
              Authorization: 'Bearer ' + this.token,
              MarinaId: '' + StorageUtil.getMarinaId(),
              UserId: '' + StorageUtil.getUserId(),
              integrationKey: '' + StorageUtil.getMarinaIntegrationKey(),
              OriginEasy: 'EasyWeb',
              'Access-Control-Allow-Origin': '*',
            });
          }
        }
        console.log("linha 65")
        console.log(request)
        request = request.clone({headers});
        console.log("linha 68")
        console.log(request)
      }
    }
    return next.handle(request).pipe(
      filter(
        (event: any) => {
          if (event instanceof HttpResponse) {
            const token = JSON.parse(JSON.stringify(event.body.token));
            console.log("Bateu aqui 1 ")
            if (token && token.length > 0) {
              StorageUtil.saveToken(token);
            }
          }
          return event;
        },
        async (err: any) => {
          if (err.status === 0) {
            this.messageUtil.generateMessage(
              'error',
              'SUMMARY.ERROR',
              'Ocorreu uma falha de comunicação com o servidor.',
              3000
            );
            return;
          }
        }
      ),
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401 && !this.swal) {
          if (
            error.url.includes('authenticate') //TODO criar uma pagina de roteamento onde ira levar o usuario informando que a sessão expirou, ele deve logar novamento pelo easy marine. Apresentar um Swal como mensagem
          ) {
            throw error;
          }

          const token = StorageUtil.getToken();
          console.log("Linha 104")
          const headers = new HttpHeaders({
            'Content-Type': 'application/json',
            userId: StorageUtil.getUserId().toString(),
            marinaId: StorageUtil.getMarinaId().toString(),
            token: StorageUtil.getMarinaIntegrationKey()
          });
          console.log(headers);
          request = request.clone({headers})
          console.log(request)
          if (!token) {
            return this.http
              .post(
                environment.apiHost + '/authentication/login',
                '',
                {headers: headers}
              )
              .pipe(mergeMap((resp: any) => {
                  try {
                    console.log("Bateu aqui??")
                    const token = JSON.parse(JSON.stringify(resp.data.token));
                    if (token) {
                      StorageUtil.saveToken(token);
                      const reqConst = request.clone({
                        setHeaders: {
                          Authorization: 'Bearer ' + token,
                        },
                      });
                      return next.handle(reqConst);
                    }
                  } catch (error) {
                    this.swal = Swal.fire('WARNING', 'Sua sessão expirou.', 'warning');
                  }
                  return throwError(error);
                })
              );
          } else {
            this.swal = Swal.fire('WARNING', 'Sua sessão expirou.', 'warning');
          }
        }
        throw error;
      })
    );
}

请求帮助排查HttpHeaders创建失效的问题。

内容的提问来源于stack exchange,提问作者rafaelpadu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:35:22