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

Angular中localStorage未定义错误的解决求助

解决Angular SSR中"localStorage is not defined"错误的方案

核心问题分析

你的Angular应用启用了SSR(服务器端渲染),而Node.js服务器环境本身没有localStorage API。虽然你添加了polyfill,但拦截器和存储服务在服务器初始化阶段就直接调用了localStorage,导致错误依然存在。以下是具体修复步骤:


1. 修复LocalStorageService,加入平台环境判断

在存储服务中注入PLATFORM_ID,判断当前是否处于浏览器环境,仅在浏览器端执行localStorage操作:

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root',
})
export class LocalStorageService {
  private isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.isBrowser = isPlatformBrowser(this.platformId);
  }

  setItem(key: string, value: string) {
    if (this.isBrowser) {
      localStorage.setItem(key, value);
    }
  }

  getItem(key: string) {
    if (this.isBrowser) {
      return localStorage.getItem(key);
    }
    return null;
  }
}

2. 调整AuthInterceptor,避免无效请求头

当服务器端获取到的token为null时,不要添加Authorization头,避免生成无效的Bearer null请求头:

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { LocalStorageService } from '../services/local-storage-service.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private localStorageService: LocalStorageService) {}

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

    let token = this.localStorageService.getItem('token');
    let newRequest: HttpRequest<any> = req;

    // 仅当token存在时,才添加Authorization请求头
    if (token) {
      newRequest = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + token),
      });
    }

    return next.handle(newRequest);
  }
}

3. 优化server.ts中的polyfill加载顺序(可选)

确保polyfill在Angular模块加载前生效,将polyfill导入放在server.ts最顶部:

import 'localstorage-polyfill';
global['localStorage'] = localStorage;

// 其余导入和代码保持不变
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import express from 'express';
// ...后续代码

内容的提问来源于stack exchange,提问作者Şahin Yakıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:05