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

Angular 17 SSR下Interceptor未触发及localStorage未定义问题求助

Angular 17 SSR:解决Interceptor未触发与localStorage undefined问题

一、修复Interceptor未触发的问题

你的Interceptor注册代码中存在名称不匹配的问题:实际定义的Interceptor是KleverInterceptor,但注册时写的是NeosparkInterceptor,导致框架无法识别并加载该拦截器。

修正app.config.ts中的注册代码:

export const appConfig: ApplicationConfig = { 
  providers: [ 
    provideRouter(routes),
    provideClientHydration(),
    // 将NeosparkInterceptor改为KleverInterceptor
    provideHttpClient(withFetch(), withInterceptors([KleverInterceptor])),
  ]
}

二、解决localStorage undefined错误

Angular SSR在服务器端渲染阶段运行于Node.js环境,该环境不存在localStorage对象,直接调用会抛出undefined错误。需要先判断当前运行环境是否为浏览器,再执行localStorage相关操作。

修改后的Interceptor代码:

import { HttpInterceptorFn } from '@angular/common/http';
import { inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

export const KleverInterceptor: HttpInterceptorFn = (req, next) => {
  const platformId = inject(PLATFORM_ID);
  let token: string | null = null;

  // 仅在浏览器环境下读取localStorage
  if (isPlatformBrowser(platformId)) {
    token = localStorage.getItem("token");
    console.log("Interceptor token", token);
  }

  // 有token时才添加Authorization头
  const authReq = token 
    ? req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) })
    : req;

  console.log("interceptor triggered");
  return next(authReq);
};

额外说明

如果需要在服务器端渲染时也携带token请求API,仅靠localStorage无法实现(服务器端无法读取客户端存储)。可以考虑:

  • 登录时将token同时存入HttpOnly Cookie,服务器端可直接从Cookie中读取
  • 使用Angular的TransferState API,将客户端的token传递到服务器端

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:11:07