headers.set无法设置Authorization header致Angular 5 JWT 401授权失败
Hey there, let's break down why your Angular 5 code is hitting a 401 while Postman works perfectly—this is usually a header formatting or setup issue in your Angular code. Here are the key things to check step by step:
1. Double-check the Authorization Header Format
The most common mistake here is forgetting the Bearer prefix. JWT headers must follow the format:
Authorization: Bearer <your-jwt-token>
Make sure your code includes this explicitly. For example:
headers.set('Authorization', 'Bearer ' + yourJwtToken);
A missing space between Bearer and the token, or omitting Bearer entirely, will almost always trigger a 401.
2. Verify Header & Request Setup in Angular 5
Angular 5 uses the older Http module (not HttpClient introduced in Angular 4.3), so your request setup needs to match that. Here's the correct pattern:
import { Http, Headers, RequestOptions } from '@angular/http'; // Inside your service/component method const token = localStorage.getItem('authToken'); // Or wherever you store the token let headers = new Headers(); headers.set('Authorization', 'Bearer ' + token); // Add any other headers you need (like Content-Type) headers.set('Content-Type', 'application/json'); const options = new RequestOptions({ headers: headers }); this.http.post('your-api-endpoint', requestBody, options) .subscribe( response => console.log('Success!', response), error => console.error('401 Error:', error) );
Ensure you're not accidentally overwriting the headers object later in your code before sending the request.
3. Inspect the Actual Request in Browser DevTools
Open your browser's DevTools (F12), go to the Network tab, and find your failed request. Check the Request Headers section for:
- Does the
Authorizationheader exist? - Is it formatted correctly (
Bearer <token>)? - Is the token exactly the same as the one you used in Postman?
If the header is missing entirely, that means your code isn't attaching it properly to the request.
4. Check for Interceptor Conflicts
If you have a global HTTP interceptor in your app, it might be overriding or removing your Authorization header. Look for code that implements Angular 5's interceptor pattern and ensure it's not modifying the headers in a way that breaks your JWT auth.
5. Rule Out CORS Preflight Issues
Postman skips CORS preflight checks, but browsers send an OPTIONS request before your actual POST/GET. If your server rejects the OPTIONS request with a 401, that'll block your main request. Verify that your server is configured to allow OPTIONS requests without requiring an Authorization header.
6. Test with a Minimal Request
Strip down your code to the simplest possible request to eliminate variables. For example:
// Minimal test request this.http.get('your-protected-api-url', { headers: new Headers({ 'Authorization': 'Bearer ' + tokenFromPostman }) }).subscribe( res => console.log('Request succeeded!', res), err => console.error('Error details:', err) );
Use the exact same token from Postman here—if this still fails, the issue is definitely in how Angular is sending the header; if it works, then your token retrieval/storage code is the problem.
内容的提问来源于stack exchange,提问作者imin

