Keywords: CORS | Preflight Request | Authorization Header | Cross-Origin Resource Sharing | OPTIONS Method | Node.js Configuration | AngularJS Frontend | Browser Security Policy
Abstract: This technical article provides an in-depth analysis of the common CORS error 'Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response' encountered in AngularJS frontend and Node.js backend cross-origin requests. It explains the CORS preflight mechanism, highlights the critical role of the OPTIONS method, and presents comprehensive solutions including manual header configuration and using the cors middleware. The article also explores browser security implications and offers best practices for robust cross-origin communication.
Understanding CORS Preflight Request Mechanism
Cross-Origin Resource Sharing (CORS) is a crucial mechanism in modern web development for handling cross-origin requests. When browsers detect cross-origin requests containing custom headers like Authorization, they first send an OPTIONS preflight request to the target server. This preflight request serves to verify whether the server permits the actual request.
In the described scenario, an AngularJS frontend runs on one local port while a Node.js backend operates on another, creating a typical cross-origin environment. Before sending the actual GET request with the Authorization header, the browser automatically initiates an OPTIONS preflight request.
Deep Analysis of the Error Cause
Although the original code configured Access-Control-Allow-Headers to include Authorization, there was a critical omission: the server didn't properly handle the OPTIONS method. When the preflight request arrives, the server must explicitly declare that it allows the OPTIONS method; otherwise, the browser will reject subsequent actual requests.
From a technical perspective, preflight requests contain two important headers: Access-Control-Request-Method declares the method of the actual request (GET), and Access-Control-Request-Headers declares the headers that the actual request will carry (Authorization). The server must explicitly permit these methods and headers through response headers.
Complete Solution Implementation
In the Node.js backend, ensure the OPTIONS method is properly allowed. Here's the corrected code example:
// Basic configuration to allow all cross-origin requests
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, PATCH, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
// Handle OPTIONS preflight requests
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});The key improvement is adding OPTIONS to Access-Control-Allow-Methods and specifically handling OPTIONS requests. When the browser sends a preflight request, the server returns a 200 status code, indicating permission for the subsequent actual request.
Simplifying Configuration with cors Middleware
For a more streamlined solution, using the Node.js cors package is recommended. First install via npm:
npm install corsThen configure in your application:
const cors = require('cors');
// Basic configuration
app.use(cors());
// Or custom configuration
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
}));The cors middleware automatically handles all preflight request logic, significantly simplifying development work. It automatically returns appropriate response headers for OPTIONS requests without manual intervention.
Frontend Code Optimization Suggestions
In the AngularJS service, ensure the Authorization header format is correct. The original code's string concatenation might have spacing issues:
return {
getValues: $resource(endpoint + '/admin/getvalues', null, {
'get': {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + $localStorage.token // Note the space after Bearer
}
}
})
};Ensure token values are properly stored and retrieved to avoid authentication failures due to format issues.
Security Considerations and Best Practices
Although the example uses Access-Control-Allow-Origin: '*' to allow all origins, production environments should restrict to specific domains:
res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');If credentials (like cookies) need to be included, also set:
res.header('Access-Control-Allow-Credentials', 'true');And configure the frontend request with withCredentials: true.
Debugging and Testing Methods
Use browser developer tools' network panel to observe the request flow:
- Confirm if the OPTIONS preflight request succeeds (status code 200)
- Check if response headers contain correct CORS headers
- Verify if the actual request carries the Authorization header
Tools like Postman can be used to test API endpoints independently, confirming backend logic correctness and isolating frontend configuration issues.
Conclusion
The CORS preflight mechanism is an essential component of browser security policies. Understanding the role of the OPTIONS method in cross-origin requests and properly configuring server response headers are key to resolving such issues. Both manual configuration and using the cors middleware can effectively handle Authorization header usage in cross-origin requests. Thorough testing across various scenarios during development is recommended to ensure stable and reliable cross-origin functionality.