Fixing CORS Policy Issues: Step-by-Step

CORS errors happen when your browser stops your app from talking to another website or API because it doesn’t trust it yet. 

Don’t worry—it’s a common issue, and there are easy ways to fix it. Let’s break it down.

What is CORS?

CORS is a security rule that browsers follow. It checks if your app has permission to ask another website (or API) for data.

If the permission isn’t set up correctly, the browser blocks the request and shows an error like:

“Blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

Two Common Scenarios for CORS Errors

  1. When you call an API from the backend (server-side).
  2. When you call an API directly from the browser (client-side).

Let’s fix each case step by step.

1. Fixing CORS for Server-Side API Calls

If your app makes requests from the backend (like Node.js or another server), you need to adjust the server’s settings.

How to Fix:

  • Tell the server to allow requests from your app.
  • This is done by adding your app’s domain or IP address to the server’s “allowed list.”
  • After this, the server will process your requests without any errors.

Example:

Imagine your server is a security guard. You give it a list of people (domains or IPs) who are allowed to enter. Once your app is on the list, the guard (server) lets it in!

2. Fixing CORS for Client-Side API Calls

When you call an API directly from the browser using JavaScript, the browser might block it because the server didn’t say, “It’s okay to share data with your app.”

What You’ll See:
An error message like this:

Access to XMLHttpRequest at ‘http://yourdomain.com/rest/services/sendSMS/sendGroupSms?AUTH_KEY=tgdfsrgdfghdf&message=dthisistestsms&senderId=SGRHSP&routeId=11&mobileNos=999999999&smsContentType=English

Error:

From origin’http://localhost:5173‘ has been blocked by CORS policy:  

No ‘Access-Control-Allow-Origin’ header is present on the requested resource. 

How to Fix:

Add an option called mode: ‘no-cors’ to your API call. This tells the browser to stop checking the CORS rules.

Example Code

Here’s a simple example to show how you can fix this issue in your code:

Example of a Client-Side Fix

Here’s how you can modify your JavaScript code:

Sample Code:

document.getElementById(‘sendSmsButton’).addEventListener(‘click’, () => {  

    const apiUrl = ‘https://yourdomain.net/rest/services/sendSMS/sendGroupSms?AUTH_KEY=dfgdfg&message=Hello&senderId=TBTSIG&routeId=1&mobileNos=9999999999&smsContentType=English‘;

    fetch(apiUrl, {  

        method: ‘GET’,  

        mode: ‘no-cors’,  

    })  

        .then(response => {  

            if (!response.ok) {  

                throw new Error(`HTTP error! Status: ${response.status}`);  

            }  

            return response.json();  

        })  

        .then(data => {  

            console.log(‘Response:’, data);  

            alert(‘SMS Sent Successfully!’);  

        })  

        .catch(error => {  

            console.error(‘Error:’, error);  

            alert(‘Failed to send SMS!’);  

        });  

});  

Key Points to Remember

  • Use mode: ‘no-cors’ for quick fixes in client-side API calls.
  • Always ensure your server allows requests from the required domain or IP.

By following these simple steps, you can resolve CORS issues and make your API calls work smoothly.