Angular 5 HttpInterceptor忽略登录请求问题求助
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
authTokenisnull—add that logic in the finalreturnblock 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

