Cross-Origin Resource Sharing (CORS) is a security mechanism enforced by web browsers to prevent unauthorized cross-origin requests. When an AngularJS app running on one domain (http://localhost:4200
) tries to make an API request to another domain (https://api.example.com
), the browser blocks the request unless the server allows it.
In this guide, we will cover:
- Understanding CORS and Why It Matters
- Common CORS Errors in AngularJS
- Configuring CORS on the Server
- Making CORS Requests in AngularJS
- Using
$httpProvider.defaults
for Global CORS Configuration - Handling CORS with Custom Headers and Credentials
- Using a Proxy to Bypass CORS in Development
- Using JSONP as a Workaround (Limited Use Case)
- Best Practices for Handling CORS in AngularJS
1. Understanding CORS and Why It Matters
CORS is a security feature implemented in browsers to prevent unauthorized API access from different origins.
An origin consists of:
- Protocol (HTTP, HTTPS)
- Domain (
example.com
) - Port (
:3000
,:8080
)
For example:
- Allowed:
https://example.com
→https://api.example.com
(if CORS is enabled) - Blocked:
http://localhost:4200
→https://api.example.com
(without CORS headers)
How CORS Works
When an AngularJS app sends a cross-origin request, the browser:
- Sends a “preflight” OPTIONS request (for complex requests like
PUT
,DELETE
, or custom headers). - Checks server response headers to verify CORS permissions.
- Allows or blocks the actual request based on the server’s response.
2. Common CORS Errors in AngularJS
You may encounter errors like:
CORS policy error:
“Access to fetch at ‘https://api.example.com‘ from origin ‘http://localhost:4200‘ has been blocked by CORS policy.”
Preflight request failure:
“Response to preflight request doesn’t pass access control check.”
These errors occur because the server does not return the correct CORS headers.
3. Configuring CORS on the Server
The best way to handle CORS is to configure your server to allow cross-origin requests.
Example: Enabling CORS in Different Backends
Node.js (Express)
Install the cors
package:
npm install cors
Modify your server:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors()); // Allow all origins
app.get('/data', (req, res) => {
res.json({ message: "CORS enabled!" });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Python (Flask)
Install Flask-CORS:
pip install flask-cors
Modify your server:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/data')
def home():
return {"message": "CORS enabled!"}
app.run(port=5000)
Apache Server
Modify .htaccess
:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, DELETE, PUT"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
Nginx
Modify nginx.conf
:
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
4. Making CORS Requests in AngularJS
If the server supports CORS, you can make cross-origin API calls using $http
.
Example: Basic $http
Request
app.controller('MainController', function($scope, $http) {
$http.get('https://api.example.com/data')
.then(response => {
$scope.data = response.data;
})
.catch(error => {
console.error('CORS error:', error);
});
});
If CORS is not enabled on the server, this request will be blocked.
5. Using $httpProvider.defaults
for Global CORS Configuration
You can configure $httpProvider.defaults
to set CORS headers for all requests.
Enable CORS Globally in AngularJS
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
6. Handling CORS with Custom Headers and Credentials
If your API requires authentication (e.g., JWT tokens), the server must allow credentials.
Modify Server to Allow Credentials
app.use(cors({
origin: 'http://localhost:4200',
credentials: true
}));
Enable Credentials in AngularJS
$http({
method: 'GET',
url: 'https://api.example.com/data',
withCredentials: true
});
7. Using a Proxy to Bypass CORS in Development
If you don’t control the server, you can set up a proxy to avoid CORS issues.
Example: Proxy in AngularJS Development
Modify proxy.conf.json
:
{
"/api": {
"target": "https://api.example.com",
"secure": false,
"changeOrigin": true
}
}
Start AngularJS with:
ng serve --proxy-config proxy.conf.json
Now, use /api/data
instead of https://api.example.com/data
.
8. Using JSONP as a Workaround (Limited Use Case)
JSONP is an alternative to CORS but only works for GET
requests.
Enable JSONP in AngularJS
app.controller('MainController', function($scope, $http) {
$http.jsonp('https://api.example.com/data?callback=JSON_CALLBACK')
.then(response => {
$scope.data = response.data;
});
});
Your API must support JSONP for this to work.