Angular 7授权异常:拦截器实现认证时出现401未授权错误
Hey there, let's dig into why your Angular HttpInterceptor is triggering a 401 error even though you're adding the Authorization token, while Postman requests work perfectly. I've got a few common culprits to check off one by one:
1. Fix the extra space in your request URL
Looking at your error message, the target URL has an unexpected trailing space:
http://localhost/Invoicing/api/users/settings/getTableColumns/leads-list
This tiny whitespace can throw off backend routing or token validation logic entirely. Double-check where you're initiating this request in your frontend code—make sure there's no accidental space added to the URL string.
2. Verify your token's validity and format
Even though Postman works, confirm that the this.authService.token value your interceptor is using matches exactly what you're pasting into Postman. Watch out for:
- Accidental extra spaces before/after the token
- Expired tokens (your frontend might be storing an old token while Postman uses a fresh, valid one)
- Typos or case mismatches in the token string
Add a quick console log in the interceptor to inspect the token being sent:
console.log('Token being sent:', `Bearer ${this.authService.token}`);
3. Check header formatting and case sensitivity
Some backend frameworks are picky about header casing or formatting. Ensure your Authorization header is properly structured as Bearer <token> with no extra spaces. You can also log the final request headers to confirm they're set correctly:
req = req.clone({ headers: req.headers.set('Authorization', `Bearer ${this.authService.token}`) }); console.log('Request headers:', req.headers);
Verify the Authorization key exists and has the exact value you expect.
4. Rule out CORS issues
Postman doesn't enforce CORS restrictions, but browsers do. If your backend isn't configured to allow the Authorization header in CORS responses, the browser might strip it before sending the actual request.
Check your browser's Network tab for the OPTIONS preflight request. Its response headers should include:Access-Control-Allow-Headers: Authorization
If not, you'll need to update your backend's CORS configuration to explicitly allow this header.
5. Confirm your interceptor is properly registered
Make sure your interceptor is added to your AppModule's providers array correctly—without this, it won't run at all:
@NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthenticationInterceptor, multi: true }, { provide: 'IAuthService', useClass: AuthService } ] }) export class AppModule { }
The multi: true flag is critical here—it tells Angular to add your interceptor to the existing chain instead of replacing it.
6. Check for conflicting interceptors
If you have other HttpInterceptors in your project, one of them might be overwriting or removing your Authorization header. Try temporarily disabling other interceptors to see if the request starts working.
Quick test: Try using append instead of set
While set works if there's no existing Authorization header, using append can prevent accidental overwrites if some requests already have the header:
req = req.clone({ headers: req.headers.append('Authorization', `Bearer ${this.authService.token}`) });
Start with the URL space issue first—it's the most obvious red flag in your error message. If that doesn't fix it, work through the other checks one by one.
内容的提问来源于stack exchange,提问作者3xGuy

