How to Fix CORS Issue “No ‘Access-Control-Allow-Origin’ Header Present” in REST API?

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 is CORS, 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 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 their 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 your used 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!
quiz-icon

The Role of the Access-Control-Allow-Origin Header

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

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, at production, it is not recommended to do. Besides, this it is more good to allow only specific domains to get access of 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 intermediatory 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” then, 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. 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.

Advantages and Disadvantages 

You can use multiple methods to avoid or remove CORS errors. However, each method has its own advantages and disadvantages. Here are as following:

Solutions Advantages Disadvantages
Allowing * domains Easy to implement Security risk, open to all origins
Allowing specific origins More secure Requires maintenance as client domains change
Using a Proxy Server Bypasses CORS restrictions Additional configuration needed
Browser Extension Quick fix for development Not recommended for production

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.

No ‘Access-Control-Allow-Origin’ Header is Present on the Requested Resource – FAQs

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.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner