You may find this error, “No ‘Access-Control-Allow-Origin’ header is present on the requested resource,” while fetching data from the REST API. This issue is caused by Cross-Origin Resource Sharing (CORS), a security feature that was imposed by web browsers to prevent unauthorized access to resources from different origins or ports. This will protect your resources from unauthorized people, but at the same time, this will make it difficult for developers to work with the API to get data.
In this blog, we will break down what CORS is, why this error occurs, and how you can fix this error in different working environments like Apache, Nginx, and more.
Table of Contents:
What is CORS?
CORS stands for Cross-Origin Resource Sharing. It is a security protocol that is imposed by the web browsers that control your server resources. It also ensures that your server resources are not accessed by any other origins.
Let’s consider an example to understand more about CORS. Suppose your frontend application is hosted at http://Intellipaat.frontend.com, and the REST API is hosted at http://Intellipaat.api.com. Now, when your frontend tries to get data from the API, the browser blocks the request until the API explicitly does not allow the frontend origin to get its data. This security feature prevents malicious websites from getting data without permission.
Understanding the Error
Let’s say you run this JavaScript fetch request by writing this code:
fetch("http://api.Intellipaat.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch
(error => console.error("Error:", error));
If “http://api.Intellipaat.com/data” does not include the Access-Control-Allow-Origin header in its response, then your browser blocks the request, and you will see the following error in the console:
Access to fetch at 'http://api.Intellipaat.com/data' from origin 'http://Intellipaat.frontend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
In short, this error simply means that you used the API (here, http://api.Intellipaat.com/data) didn’t grant permission to access its resources.
Kickstart Your Career in Tech With Hands-On Web Development Training
Start Your Web Development Journey Today!
The Access-Control-Allow-Origin header tells the browser whether it should allow a web application running on one domain to access resources from another domain or not. You can pass different values to the header:
- Access-Control-Allow-Origin: * This means you can allow all domains to access the resources from the REST API.
- Access-Control-Allow-Origin: http://Intellipaat.frontend.com – It will allow only this specific domain to access resources. You can pass the domain value that you want.
- Access-Control-Allow-Origin: null Blocks all cross-origin requests
Understanding CORS Preflight Requests
When a browser issues certain types of cross-origin requests, like when it tries to use PUT, DELETE, or a custom header, it first sends a preflight request using the HTTP OPTIONS method. This request checks to see if the actual request is safe to send. The server needs to respond with appropriate headers, such as:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
If the required permissions are not specified by the response, the browser will block the actual request from completing. So, configuring these headers to add those permissions is required to avoid errors during cross-origin API communications.
How to Fix CORS Issues
There are multiple ways to fix CORS issues. Here are some of them :
Method 1: Configuring CORS on the Server Side
The best way to resolve CORS errors is to configure the API server code.
1. Fixing CORS in Node.js
If you’re using Express.js to build your server, then you can enable CORS by adding a middleware.
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
app.get('/data', (req, res) => {
res.json({ message: "CORS issue fixed!" });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Explanation:
In the above code, res.header(“Access-Control-Allow-Origin”, “*”). This line allows all the domains to get the data from the API. But, in production, it is not recommended to do so. Besides, it is better to allow only specific domains to access your server resources.
2. Fixing CORS in Apache
If your API is hosted on an Apache server, then update your .htaccess file by writing this line.
Header set Access-Control-Allow-Origin "*"
3. Fixing CORS in Nginx
For Nginx, add these few lines to your server configurations.
server {
location / {
add_header 'Access-Control-Allow-Origin' 'http://127.0.0.1:5173';
}
}
Method 2: Use a Proxy Server
If you are not making an API or don’t have control over the API, then another way to remove this CORS error is to use a proxy server that helps you bypass CORS restrictions. In this method, you’re sending the requests from your frontend to an intermediate server, and that intermediary server(proxy) then forwards the request to the actual API.
For Node.js (Proxy Server)
To set up a proxy server to get access to the server resources made using Node.js, you have to use the http-proxy-middleware package.
const { createProxyMiddleware } = require('http-proxy-middleware');
const express = require('express');
const app = express();
app.use('/api', createProxyMiddleware({
target: 'http://api.Intellipaat.com',
changeOrigin: true
}));
app.listen(3000, () => console.log('Proxy server running on port 3000'));
Explanation:
Now, when the frontend requests to “http://localhost:3000/api”, the proxy server redirects this request to “http://api.Intellipaat.com”. Since now the request comes from a proxy(not from the frontend) the browser does not block this request due to CORS.
Method 3: Use Browser Extensions
At the time of development, you can also use some browser extensions to remove this CORS error. However, this is not a recommended step because it is a temporary solution that fails when the project is deployed. Sometimes, browser caching effects can also make it seem like the CORS issue still exists, even after making the correct server-side changes. Clearing your browser cache or using an incognito window can help confirm whether the error is truly fixed. These extensions are:
- Moesif CORS
- Allow CORS: Access-Control-Allow-Origin
Security Considerations
Many people make these common mistakes. You can avoid these mistakes while fixing the CORS errors:
- Didn’t allow all origins ( * ), only allowed trusted domains.
- Ensure the authentication mechanisms, like API tokens and OAuth, are applied successfully.
- When APIs require credentials like cookies or tokens, CORS must be configured to allow them. Without this, browsers block even authorized requests.
To handle this securely, include the following in your server code, res.header("Access-Control-Allow-Credentials", "true");
And on the frontend, fetch(url, { credentials: "include" });
This combination ensures secure and successful data exchange between the client and server.
Advantages and Disadvantages of Various CORS Handling Methods
You can use multiple methods to avoid or remove CORS errors. However, each method has its own advantages and disadvantages. Here are as following:
| Method |
Advantages |
Disadvantages |
| Configuring CORS on the Server (Recommended) |
Permanent and secure fix for the “No Access-Control-Allow-Origin” error; follows best practices. |
Requires backend/server access and careful setup of headers. |
Allowing All Origins (*) |
Quick temporary fix during development; removes CORS restriction instantly. |
Not secure for production; fails for authenticated or credentialed requests. |
| Allowing Specific Origins |
Secure and reliable; only trusted domains can access API resources. |
Needs updates whenever frontend domain changes. |
| Using a Proxy Server |
Works even when you don’t control the target API; bypasses CORS restrictions. |
Adds extra layer of configuration and may affect performance. |
| Using Browser Extensions |
Simple, instant fix for local testing and debugging. |
Temporary solution; not suitable or safe for production use. |
| Handling CORS Preflight Requests Properly |
Ensures complex requests (like PUT, DELETE, custom headers) don’t get blocked. |
Must correctly configure OPTIONS method and allowed headers. |
| Enabling Credentials for Authenticated APIs |
Allows secure access for APIs requiring tokens or cookies. |
Cannot combine with wildcard origin (*); requires strict setup. |
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
Handling CORS issues correctly can allow you to do multiple API integrations in your code. The best way to fix CORS errors is by configuring the server to include proper Access-Control-Allow-Origin headers. Avoid using temporary fixes like browser extensions for industry-level production applications.
These articles provide an essential guide to getting started with General Programming and Power BI–
JSON vs JavaScript Object Literal – Understand Compares JSON and JavaScript object literals, highlighting syntax, usage, and differences explained clearly.
How to parse HTML in C# – Learn how Shows how to extract and manipulate HTML content using C# and libraries like HtmlAgilityPack to improve your coding.
Data preparation in Power BI – Explains shaping, cleaning, and combining data sources.
Power BI RANKX vs SQL ROW_NUMBER – Highlights performance and flexibility differences.
Q1. What is the “No ‘Access-Control-Allow-Origin’ header present on the requested resource” error?
This error occurs when the frontend side of a web application wants to fetch data from the backend server without its permission. Browsers apply the Same Origin Policy to prevent malicious activities.
Q2. Is it safe to set 'Access-Control-Allow-Origin' to '*'?
Setting ‘Access-Control-Allow-Origin’ to ‘*’ allows any domain to access the resources, which can put your website resources at risk.
Q3. Why do I still get CORS errors after setting the 'Access-Control-Allow-Origin' header?
If other required headers are absent or incorrectly set up, CORS issues can still occur. As an example, the server may need to process preflight requests by responding to OPTIONS requests with ‘Access-Control-Allow-Methods‘ and ‘Access-Control-Allow-Headers‘ headers. Also, having multiple values for the ‘Access-Control-Allow-Origin’ header may lead to problems, make sure that only one header is sent per response.
Q4. How can I resolve CORS errors if I don't control the server?
If you don’t have control over the server, then use a proxy server to pass your requests. The proxy makes the request to the target server and then sends the data back to your application.
Q5. How does the browser handle CORS preflight requests?
For some requests, particularly non-trivial GET or POST requests, browsers make a preflight OPTIONS request to the server to ask whether the real request may be safely sent. The server will need to reply with the correct CORS headers to authorize the actual request. If these headers are absent or incorrect, the browser will reject the request.