Keywords: CORS | Cross-Origin Requests | Axios Configuration | Same-Origin Policy | Preflight Requests
Abstract: This article provides an in-depth analysis of CORS errors encountered when making cross-origin API calls with Axios. By examining the Same-Origin Policy and CORS mechanism, it explains the role of Access-Control-Allow-Origin response headers and offers standard solutions including server-side configuration and reverse proxy setup. With practical code examples, developers can understand and properly resolve common cross-origin request issues.
Understanding CORS Error Mechanisms
When browsers execute cross-origin requests, they enforce the Same-Origin Policy as a security measure. This policy requires that the request origin (protocol, domain, port) must exactly match the current page origin, otherwise the browser blocks the request. In development environments, a common scenario involves local development servers (e.g., http://localhost:8080) attempting to access external API services (e.g., https://example.restdb.io), which constitutes a cross-origin request.
CORS Preflight Request Mechanism
For non-simple requests, browsers first send an OPTIONS preflight request. The preflight includes Access-Control-Request-Method and Access-Control-Request-Headers headers, and the server must respond with corresponding Access-Control-Allow-Methods and Access-Control-Allow-Headers to authorize the actual request. If preflight fails, the browser will not send the main request.
Common Error Analysis
In the described problem, the developer first encountered No 'Access-Control-Allow-Origin' header present error, indicating the server lacked CORS response headers. Subsequently attempting to add Access-Control-Allow-Origin in request headers was incorrect, as CORS headers are response headers, not request headers, leading to Access-Control-Allow-Headers in preflight response error.
Standard Solution Approaches
Proper solutions require configuring CORS response headers on the server side. Here are several standard methods:
Server-Side CORS Header Configuration
For controllable servers, appropriate CORS headers should be added to responses. Using Node.js Express as an example:
const express = require('express');
const app = express();
app.get('/api/data', (req, res) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, x-apikey');
res.json({ data: 'example response' });
});
app.listen(3000);
Using Reverse Proxy
When target server configuration cannot be modified, set up a reverse proxy. Nginx configuration example:
server {
listen 8080;
location /api/ {
proxy_pass https://example.restdb.io/;
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
add_header Access-Control-Allow-Headers 'x-apikey, Content-Type' always;
if ($request_method = OPTIONS) {
return 204;
}
}
}
Development Environment Solutions
In development environments, utilize development server proxy capabilities. For Create React App, add to package.json:
{
"proxy": "https://example.restdb.io"
}
Then modify Axios requests to point to local proxy:
axios.get('/rest/mock-data', {
headers: {
'x-apikey': 'API_KEY'
}
})
Axios Configuration Considerations
When using Axios, avoid setting CORS-related headers in request headers; these should be set by the server in responses. Proper Axios configuration should focus on business logic headers:
axios.get('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token',
'x-custom-header': 'value'
},
withCredentials: false // Cross-origin requests typically don't need credentials
})
Security Considerations
In production environments, avoid using Access-Control-Allow-Origin: * and instead specify trusted origins:
res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');
For requests requiring credentials, also set:
res.header('Access-Control-Allow-Credentials', 'true');
Debugging Techniques
Use browser developer tools to inspect network requests, focusing on:
- Preflight request (OPTIONS) response headers
- CORS-related headers in actual requests
- Detailed error messages in console
By systematically understanding and applying CORS mechanisms, developers can effectively resolve various cross-origin request issues, ensuring web application security and functionality.