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

Angular 5 HttpInterceptor忽略登录请求问题求助

Fixing "Cannot read property 'token' of null" in HttpInterceptor for Login Requests

Got it, let's work through this issue together! The root cause here is your interceptor is trying to access a token that doesn't exist yet when processing the login request—since login is the very request that fetches the token for you. We need to tweak the interceptor to skip login API calls entirely, and only add token headers when we actually have a token to use.

Step 1: Define which requests to exclude

First, list out the API endpoints that don't need token authentication (like your login endpoint). We'll tell the interceptor to ignore these.

Step 2: Update your interceptor logic

Modify your interceptor to check if the current request is in the excluded list first. If it is, pass it through without touching the token. For other requests, only add the token header if the token exists.

Here's a complete example of the updated interceptor:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service'; // Your auth service that manages tokens

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  // List of endpoints to skip token checks for
  private readonly excludedEndpoints = ['/api/auth/login'];

  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // Check if this request is in our excluded list
    const isLoginRequest = this.excludedEndpoints.some(endpoint => 
      request.url.includes(endpoint)
    );

    // If it's a login request, skip token handling entirely
    if (isLoginRequest) {
      return next.handle(request);
    }

    // Get the token from your auth service (returns null if not logged in)
    const authToken = this.authService.getToken();

    // Only add the token header if we have a valid token
    if (authToken) {
      const authenticatedRequest = request.clone({
        setHeaders: {
          Authorization: `Bearer ${authToken}`
        }
      });
      return next.handle(authenticatedRequest);
    }

    // If no token exists and it's not a login request, you can either:
    // 1. Pass the request through as-is (not recommended for protected routes)
    // 2. Redirect to login page (better for security)
    // For now, we'll pass it through to avoid errors, but adjust based on your needs
    return next.handle(request);
  }
}

Step 3: Ensure your AuthService handles token retrieval correctly

Make sure your AuthService has a method that safely returns the token or null when it doesn't exist. For example:

// Example AuthService method
getToken(): string | null {
  return localStorage.getItem('authToken');
}

Key Notes:

  • Precise matching: If you need exact URL matches instead of partial ones, use a regex instead of includes(). For example:
    const isLoginRequest = this.excludedEndpoints.some(endpoint => 
      new RegExp(`^${endpoint}$`).test(request.url)
    );
    
  • Add other excluded endpoints: If you have other public endpoints (like registration, password reset), add them to excludedEndpoints.
  • Security for protected routes: For non-login, non-public routes where a token should exist, you might want to redirect to the login page if authToken is null—add that logic in the final return block if needed.

This setup will make sure your login request skips the token check entirely, eliminating the "Cannot read property 'token' of null" error, while still adding the token header to all subsequent authenticated requests once the token exists.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:44:30